JQuery tabs dynamic content with on click fadeout+fadein and slide without UI
-
11-06-2021 - |
Pregunta
I am absolutely beginner in JQuery (but I've some knowledge about JS and programming on other languages)
I have 2 aims:
- very simple tabs (or anything for controls), on click with old (active) tab content fading out and then clicked tab content fading in (same place)
- same as 1 but with horizontal content slide instead of fading. I don't want JQuery UI, because that is overkill for a simple thing of this kind and I want to learn.
Aim 1, JS:
$(function () {
$("div.tabs > div:gt(0)").hide();
$("div.tabs ul a:first").addClass('selected');
$('div.tabs ul a').click(function () {
$("div.tabs > div").fadeOut('normal', function () {
$("div.tabs > div").fadeIn('slow');
});
$('div.tabs ul a').removeClass('selected');
$(this).addClass('selected');
return false;
});
});
HTML:
<div class="tabs">
<ul>
<li><a href="#first">First</a></li>
<li><a href="#second">Second</a></li>
<li><a href="#third">Third</a></li>
</ul>
<div id="first">
<h2>First content</h2>
</div>
<div id="second">
<h2>Second content</h2>
</div>
<div id="third">
<h2>Third content</h2>
</div>
</div>
How to find active div, instead of poking all divs with $("div.tabs > div")
in fadeOut
and in fadeIn
lines?
Aim2:
I read about slideUp
and slideDown
but that is vertical, perhaps I've to use animate()
?
How? If it's too complicated than it is good for me with vertical slide...
Solución
Aim 1: Just add an active class to the current content div. See demo for altered code.
Aim 2: There are several techniques to do it w/o jQuery UI, depends on what you want to achieve and where you want to use it. See the altered demo for some sliding effects.
Otros consejos
Paul's answer simplified for aim1: without additional classes, optimized to "div" + $(this).attr('href')
and solution for fadeout is div:visible
:
$(function () {
$("div.tabs > div:gt(0)").hide();
$("div.tabs ul a:first").addClass('selected');
$('div.tabs ul a').click(function () {
var newDiv = "div" + $(this).attr('href');
$("div.tabs > div:visible").fadeOut('normal', function () {
$(newDiv).fadeIn('slow');
});
$('div.tabs ul a').removeClass('selected');
$(this).addClass('selected');
return false;
});
});
Thanks Paul.