I'm trying to find the simplest JS solution, preferably jQuery, to accomplish the following: I have a number of divs, all with the same class, that I want to simply toggle visibility of each, one at a time.
<a href="#" id="toggle-trigger">Toggle Div Visibility</a>
<div class="slide" id="slide-one"></div>
<div class="slide" id="slide-two"></div>
<div class="slide" id="slide-three"></div>
<div class="slide" id="slide-four"></div>
<div class="slide" id="slide-five"></div>
The first div, is by default, always visible via CSS.
.slide{
display:none;
}
#slide-one{
display:block;
}
I've been unable to find anything other than just toggling between two elements, not multiple items. Please let me know if I can find the answer elsewhere. Thanks
Something like this?
$('#toggle-trigger').click(function()
{
var $Current = $('.slide:visible');
var $Slides = $('.slide');
var $Next = $Current.next();
if ($Next.length == 0) $Next = $Slides.first();
$Slides.hide();
$Next.show();
});
I made a JSFiddle for it: http://jsfiddle.net/uxqBx/
Even if Wivlaro made an answer, here is different way, using class for active element instead of :visible
pseudo-selector.
Try:
$('.slide').each(function(){
$(this).show().prev().hide();
});
Or if you want to time it:
$('.slide').each(function(i){
var elt = this;
setTimeout(function(){$(elt).show().prev().hide()},i*1000);
});
wrong answer
now as a slideshow :
var current;
$(function(){
current = $('.slide').first();
SetInterval(function(){
var next = $(current).next('.slide');
if(next.length == 0)
current = $('.slide').first();
$(current).hide();
$(next).show();
},1000);
EDIT: added toggling, I thought you wanted the div to show one after another but keeping the visibility. Now it should toggle.
Sorry, something went wrong, I post it late. - http://jsfiddle.net/ZEBza/
$("#toggle-trigger").click(function() {
var opened="";
$(".slide").each(function(i, el) {
console.log(opened);
var pass = true;
if(opened!="")
{
$(el).css("display", "block");
opened = "";
pass = false;
}
if($(el).css("display")=="block" && pass)
{
opened = $(el).attr("id");
$(el).css("display", "none");
}
});
if(opened!="")
{
$(".slide:first").css("display", "block");
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.