Reputation: 2177
I am trying to replace divs on click. For that , i am using following script
$(function(){
var $containers = $("#center > div").hide();
$('div span a').each(function(i,el){
var idx = i;
$(this).click(function(e){
var $target = $containers.filter(':eq(' + idx + ')');
// Fade out visible div
if($containers.filter(':visible').not($target).length){
$containers.filter(':visible').fadeOut();
}
// Fade in new div if not already showing
$target.not(':visible').fadeIn();
e.preventDefault();
})
})
});
html code is
<div>
<div>
<span><a href="#">Home</a></span>
<span><a href="#">About us</a></span>
<span><a href="#">Specifications</a></span>
<span><a href="#">Contact us</a></span>
</div>
<div id="center">
<div class="container">
Hey , this is Home div contents
</div>
<div class="container">
Hey , this is About us div contents
</div>
<div class="container">
Hey , this is Specifications div contents
</div>
<div class="container">
Hey , this is Contact us div contents
</div>
</div>
</div>
Here all divs are hidden initially. I want to display the 1st div and other divs on click accordingly
Please help,
Thanks
Upvotes: 1
Views: 98
Reputation: 144699
var $containers = $("#center > div").hide();
$containers.first().show()
$('div span a').click(function(e){
e.preventDefault();
var ind = $(this).parent().index();
$containers.fadeOut().filter(':eq('+ind+')').fadeIn()
})
Upvotes: 1
Reputation: 66405
1) Hide all divs except first
2) On tab click, fade out all divs, and fade in the one that corresponds to the clicked index
$("#center").children().not(':first').hide();
$('div span a').click(function(ev) {
$('#center').children().fadeOut().eq($(this).parent().index()).fadeIn();
ev.preventDefault();
}
Upvotes: 1
Reputation: 4711
Try Like This
$(function(){
var $containers = $("#center > div").not(':eq(0)').hide();
$('div span a').each(function(i,el){
var idx = i;
$(this).click(function(e){
var $target = $containers.filter(':eq(' + idx + ')');
// Fade out visible div
if($containers.filter(':visible').not($target).length){
$containers.filter(':visible').fadeOut();
}
// Fade in new div if not already showing
$target.not(':visible').fadeIn();
e.preventDefault();
})
})
});
Upvotes: 1
Reputation: 4906
just replace
var $containers = $("#center > div").hide();
with
var $containers = $("#center > div").not(':first').hide();
Upvotes: 1
Reputation: 4617
Replace this
var $containers = $("#center > div").hide();
With this
var $containers = $("#center > div").not(':eq(0)').hide();
Upvotes: 1
Reputation: 14302
Use :first selector
Example :
$(function(){
var $containers = $("#center > div").hide();
$("#center > div:first").show(); // OR $containers.first().show();
// existing code
});
Upvotes: 1