Toggle visibility of three or more divs - javascript

I have a simple script that toggles the visability of two divs:
<script type='text/javascript'>
$(window).load(function(){
function toggle_contents() {
$('#page1').toggle();
$('#page2').toggle();
setTimeout(function(){
toggle_contents()
}, 25000)
}
toggle_contents();
});
</script>
<div id="container">
<div id="page1">This is page 1 contents.</div>
<div id="page2" style="display:none;">This is page 2 contents.</div>
</div>
It works great but I can not figure out how to add more divs to the mix.
http://jsfiddle.net/mxwv85px/1/
Any help is much appreciated...

To cycle through a set of divs you could use a class on the active div, and use next to move on each iteration. Something like this:
function toggle_contents() {
var $active = $('#container .active');
if ($active.length && $active.next().length) {
$active.hide().removeClass('active').next().show().addClass('active');
}
else {
$('.active').hide();
$('#container div:first').show().addClass('active');
}
setTimeout(toggle_contents, 3000)
}
toggle_contents();
Updated fiddle

.toggle() means the div's are toggled between hidden and displayed. I would suggest using .hide() and .show() instead, as this gives you more control about what content you want to display or not. However, the downside is you would need a code that has much more lines to it. Give me a second while I try to make such a thing for you.
Currently you can only have 2 divs, because the .toggle() function can only have 2 values, which means a third div will have the same value as another div, causing it to be either visible or hidden while another div is as well.
The code provided in this answer by #Rory McCrossan is already working, so I'll stop trying to program it myself:
https://stackoverflow.com/a/27447139/4274852

You could cycle through the selected elements and show only one each call
var page=0;
function toggle_contents() {
$('.page').hide();
var array = $('.page').toArray();
$(array[page]).show();
page=++page%array.length;
setTimeout(function(){toggle_contents()}, 3000)
}
toggle_contents();
http://jsfiddle.net/mxwv85px/9/

First of all, put timer out of toggle_contents function. Secondly, add to divs common class, cache them and operate with variable-cache
$(window).load(function(){
var divs = $('.some-class');
function toggle_contents() {
divs.toggle();
}
setTimeout(function(){
toggle_contents()
}, 25000)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="some-class">
</div>
<div class="some-class">
</div>
<div class="some-class">
</div>

You can do this
http://jsfiddle.net/mxwv85px/13/
The code
<div id="container">
<div id="page1">This is page 1 contents.</div>
<div id="page2" style="display:none;">This is page 2 contents.</div>
<div id="page3" style="display:none;">This is page 3 contents.</div>
<div id="page4" style="display:none;">This is page 4 contents.</div>
<div id="page5" style="display:none;">This is page 5 contents.</div>
function toggle_contents() {
var items = $('#container div');
for(var i= 0; i < items.length; i++)
{
if($(items[i]).is(":visible")) {
$(items[i]).hide();
i + 1 == items.length ? $(items[0]).show() : $(items[i+1]).show();
break;
}
}
setTimeout(function(){ toggle_contents() }, 500)
}
toggle_contents();

To add more divs, you can use .append, for example:
$('#container').append('<div id="page3">This is page 3 contents</div>');

Related

jQuery detect when scroll is within and not past a certain div

I have the following divs
<div id="item-1" >item 1 content get here </div>
<div id="item-2" >item 2 content get here </div>
I would like to execute a function when the scroll is between the div content and when the scroll goes beyond the div then execute a different function.
In my jQuery I have
$(window).on('scroll', function() {
var divs = ["item-1","item-2"]; //the above two divs
divs.forEach(function(item){
var current_div = $('#'+item).offset().top
if(current_div < window.pageYOffset) {
console.log("I have reached the div", item);
}
});
});
The above works when scrolling to the bottom, but doesn't work when scrolling to top. It also doesn't detect when I scroll beyond a certain div.
How can I detect when scroll is only with a certain div? The divs are dynamic, hence the need to use the array.
Your solution should work with the code below.
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256 QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
$(window).on('scroll', function() {
var divs = ["item-1","item-2"]; //the above two divs
divs.forEach(function(item){
var current_div = $('#'+item).offset().top
if(current_div < window.pageYOffset) {
console.log("I have reached the div", item);
}
});
});
And then your HTML
<div id="item-1" >item 1 content get here </div>
<div id="item-2" >item 2 content get here </div>
Note: The only change made is the JQuery inclusion.
Enjoy!

jQuery open close two separate div one by one with same class

I want to open and close a two separate div one by one with same class.
The below example when I first click opentab content 1 will open first time and second click content 2 will open second time.
Closing the div one by one as follow content 2 and content 1.
Reference link
Comment for further clarification. Thanks in advance.
$(document).ready(function() {
$(".opentab").on('click', function () {
$('.tabcontent').toggle('show');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Open tab
<div class="tabcontent">
Content 1
</div>
<div class="tabcontent">
Content 2
</div>
Because you'll need to know which "direction" you're going (i.e. if the next click should be opening or closing items), I'd suggest using a boolean variable to keep track. Let's call that isClosing.
Logic-wise, you are always doing one of two things:
If closing, hide the last visible
If opening, show the first hidden
(Comments included in the code)
let isClosing = true; //We need to know if we're "closing" or "opening" the items
$(".opentab").on('click', function() {
$(".tabcontent").finish(); //Skip animations if pressed rapidly
const $elementToToggle = isClosing
? $('.tabcontent:visible').last() //If "closing", toggle the last visible
: $('.tabcontent:hidden').first(); //Otherwise, toggle the first hidden
$elementToToggle.toggle('show', () => { //Callback to wait for animation to complete
if (!$(".tabcontent:visible").length) isClosing = false; //All hidden, switch to "opening"
else if (!$(".tabcontent:hidden").length) isClosing = true; //All visible, switch to "closing"
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Open tab
<div class="tabcontent">Content 1</div>
<div class="tabcontent">Content 2</div>
<div class="tabcontent">Content 3</div>
<div class="tabcontent">Content 4</div>
Hide your second div and your toggle work.
$('.tabcontent').eq(1).hide();
$(document).ready(function() {
$(".opentab").on('click', function() {
$('.tabcontent').toggle('show');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Open tab
<div class="tabcontent">
Content 1
</div>
<div class="tabcontent">
Content 2
</div>
Alternative set counter with hide and use toggle.
//$('.tabcontent').eq(1).hide();
var counter = 0;
$(".opentab").on('click', function() {
$('.tabcontent').eq(counter).hide();
counter++;
if (counter > 1) // Reset counter
counter = 0;
$('.tabcontent').toggle('show');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Open tab
<div class="tabcontent">
Content 1
</div>
<div class="tabcontent">
Content 2
</div>

Div fade in after other a href Div's are clicked

I'm trying to have a Div fade in after the user clicks two other divs.
This is what I have so far but I'm pretty sure I'm doing something wrong. I can't seem to get the div to fade in even if only one div is clicked let alone two. Any help would be appreciated! thank you so much.
<script>
$(document).ready(function(){
$('#video_overlays').hide();
$('#video_overlays').fadeIn(9000);
$('#video_overlaysanswer').hide();
$('#video_overlaysanswer').fadeIn(18000);
$('#video_overlaysanswer1').hide();
$('#video_overlaysanswer2').hide();
$('#video_overlaysanswer2').fadeIn(18000); });
</script>
<script type="text/javascript">
$(document).ready(function(){
$("video_overlaysanswer").click(function() {
var index = $(this).closest("li").index();
$("video_overlaysanswer1").eq(index).fadeIn("slow");
return false; // prevents navigation to #
});
})
</script>
<div id="video_overlays">
This is where text is
</div>
<div id="video_overlaysanswer">
answer 1
</div>
<div id="video_overlaysanswer2">
answer 2
</div>
<div id="video_overlaysanswer1">
the answer that I want to fade in once the other two div's are clicked
</div>
$(document).ready(function(){
$('#video_overlays').hide();
$('#video_overlays').fadeIn(500);
$('#video_overlaysanswer').hide();
$('#video_overlaysanswer').fadeIn(500);
$('#video_overlaysanswer1').hide();
$('#video_overlaysanswer2').hide();
$('#video_overlaysanswer2').fadeIn(500);
$("#video_overlaysanswer,#video_overlaysanswer2").click(function() {
$("#video_overlaysanswer1").fadeIn("slow");
return false; // prevents navigation to #
});
});
Try code above.It works fine.Now implement different click event fo buttons.hope this helps.
http://jsfiddle.net/szr9vpv5/

Fadein & FadeOut Divs on Loop working fine - but not showing first DIV

Right I have 3 divs that are fading in and out but there the first DIV is not working nor fading in at all, any idea why? I feel like my code is all correct?
jQuery/Javascript:
<script type="text/javascript">
$(document).ready(function() {
function fade($ele) {
$ele.fadeOut(1000).delay(4000).fadeIn(1000, function() {
var $next = $(this).next('#HomeImage');
fade($next.length > 0 ? $next : $(this).parent().children().first());
});
};
fade($('div#stretchParent > #HomeImage').first());
});
</script>
HTML:
<div id="stretchParent"><!-- Stretch -->
<div id="HomeImage"></div>
<div id="HomeImage"></div>
<div id="HomeImage"></div>
</div><!-- Stretch End -->
I cannot seem to work it out?
it is wrong to have more of the same id on the page, use class instead id.
<div id="stretchParent">
<div class="HomeImage"></div>
<div class="HomeImage"></div>
<div class="HomeImage"></div>
</div>
Javascript:
fade($('div#stretchParent > .HomeImage').first());

Move div to top after click

$(document).ready(function() {
$('div.post').click(function() {
// the clicked LI
var clicked = $(this);
// all the LIs above the clicked one
var previousAll = clicked.prevAll();
// only proceed if it's not already on top (no previous siblings)
if(previousAll.length > 0) {
// top LI
var top = $(previousAll[previousAll.length - 1]);
// immediately previous LI
var previous = $(previousAll[0]);
// how far up do we need to move the clicked LI?
var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop');
// how far down do we need to move the previous siblings?
var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight());
// let's move stuff
clicked.css('position', 'relative');
previousAll.css('position', 'relative');
clicked.animate({'top': -moveUp});
previousAll.animate({'top': moveDown}, {complete: function() {
// rearrange the DOM and restore positioning when we're done moving
clicked.parent().prepend(clicked);
clicked.css({'position': 'static', 'top': 0});
previousAll.css({'position': 'static', 'top': 0});
}});
}
});
});
How can I move a div to the top of a list of divs upon clicking a link.
eg;
<div id=1>Div One <a>Click to update</a><a>a different link</a></div>
<div id=2>Div One <a>Click to update</a><a>a different link</a></div>
<div id=3>Div One <a>Click to update</a><a>a different link</a></div>
<div id=4>Div One <a>Click to update</a><a>a different link</a></div>
<div id=5>Div One <a>Click to update</a><a>a different link</a></div>
and when you click ONLY on the link "CLICK TO UPDATE" for any div, it should move that div to the top of the page!
80% done. Thanx guys for the swift response. Preciate it to the max. Anyways thanx to #valipour I managed to get the div to move ONLY when you click on a specific link by adding a class to the link and changing my first two lines from;
$('div.post').click(function() {
// the clicked LI
var clicked = $(this);
to;
$("a.rep").click(function() {
var clicked = $(this).closest("div.post");
html code is;
<div id="wrapper">
<div class="post"><a class="rep">1 Aasdjfa</a> <a>6 Aasdjfa</a></div>
<div class="post"><a class="rep">2 Aasdjfa</a> <a>7 Aasdjfa</a></div>
<div class="post"><a class="rep">3 Aasdjfa</a> <a>8 Aasdjfa</a></div>
<div class="post"><a class="rep">4 Aasdjfa</a> <a>9 Aasdjfa</a></div>
<div class="post"><a class="rep">5 Aasdjfa</a> <a>10 Aasdjfa</a></div>
</div>
Thanks!
BUT it doesn't work with div's that were dynamically loaded? eg. I have 10 divs showing by default then I have a script that loads more divs when you scroll...this script won't move the divs in the autoload section when you click on any of them...any idea why???
If you put them all inside another wrapper div you could do
(This is now the most upto date version):
$("#wrapper a.rep").live('click', function(){
$(this).parents('.post').hide().prependTo("#wrapper").slideDown();
});
EDITED my answer. This one works. With animation aswell ;).
If you dont like animation, have just $(this).parent().prependTo("#wrapper") **
http://jsfiddle.net/2DjXW/18/
To load Divs that are dynamically added afterwards, you will have to use the 'live'. When document is ready the divs that are not there cannot have events added. But live adds the events when new are dynamically added.
New edit:
http://jsfiddle.net/tVhqz/8/
Should work now well.
give "update" class to those links that you want to do the action and then:
$("a.update").click(function()
{
var myparent = $(this).closest("div");
var parentparent = myparent.parent();
myparent.detach().prependTo(parentparent );
return false;
});
jsFiddle link: http://jsfiddle.net/g56ap/4/
NOTES:
we are keeping parentparent separately because myparent.parent() would be invalid after detach.
Ok so through a combination of #valipour and #pehmolenu scripts I was able to get what I was looking for. I have tested it only on chrome but am sure it should work on other browsers. The complete working code is below.
Javascript;
$("#wrapper a.rep").live('click', function(){
$(this).parents('.post').hide().prependTo("#wrapper").slideDown();
});
html;
<div id="wrapper">
<div class="post"><a class="rep">This will Move div</a> <a>This won't</a></div>
<div class="post"><a class="rep">This will Move div</a> <a>This won't</a></div>
<div class="post"><a class="rep">This will Move div</a> <a>This won't</a></div>
<div class="post"><a class="rep">This will Move div</a> <a>This won't</a></div>
<div class="post"><a class="rep">This will Move div</a> <a>This won't</a></div>
</div>
This will also work if you divs are loaded dynamically based on scroll!
Thanx guys! See it in action at repjesus.com! click "rep it" on any item!

Categories

Resources