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

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>

Related

Select items from different lists at the same time

This is the HTML I got to do a button click event to control selected items in more than one list.
$('#button').click(function(){
var $next = $('.section.selected').removeClass('selected').next('.section')
if ($next.length) {
$next.addClass('selected');
}
else {
$(".section:first").addClass('selected');
}
});
//On click I select next div with same class and remove selected from previous.
//How to loop? After 3 is selected, I want it to go to one again.
.selected { background:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="all">
<div class="section selected">ONE</div>
<div class="section">TWO</div>
<div class="section">THREE</div>
</div>
<div id="all">
<div class="section selected">ONE</div>
<div class="section">TWO</div>
<div class="section">THREE</div>
</div>
<br />
CLICK
However, because the items are using the same class name, at the end, the script can't decide which one is first / last item.
Can anyone give me an idea?
To get the items, use Queries like first-child, last-child and so on.
For more detals, Check jQuery API Documentation
Use this instead $(".section:first-child").addClass('selected') in your else condition

Jquery Hover - allow hover on another DIV the appears on hover of a button

I have a homepage with 4 buttons. When hovered over a button, a menu appears behind the buttons. When you hover over another button, a different colored menu appears in it's place.
Currently, I can get the buttons to show the menus, but when I hover onto the menus (and hover off the button) I lose the menu.
Here's my simple code:
Jquery at top:
$(".mybutton").hover(
function () {
$(".mybox").fadeIn();
},
function () {
$(".mybox").fadeOut();
}
);
$(".mybutton2").hover(
function () {
$(".mybox2").fadeIn();
},
function () {
$(".mybox2").fadeOut();
}
);
And my HTML:
<div class="mybox">
<div style="position: absolute;">
Item 1
Item 2
</div>
</div>
<div class="buttons">
<div class="mybutton">
/* Button image here */
</div>
<div class="mybutton2">
/* Button 2 image here */
</div>
</div>
So I need some way to keep the box that fades in active when it is hovered over. I was thinking of not doing the callback for the fadeout, and somehow only doing the fadeout if they fade off the .mybox DIV or if they hover over another button. But it's a little unclear to me how to accomplish that.
Thanks in advance.
you need to include your menu and the button inside a container and have a hover event on the container. this way your menu will be visible as long as you're hovering over the container.
here's what you need to do.
declare the container like this with your menu and button both inside it.
<div id='container'>
<div class="mybox box">
<div style="position: absolute;">
Item 1
Item 2
</div>
</div>
<div class="buttons">
<div class="mybutton">
/* Button image here */
</div>
</div>
</div>
here's what you need to do in jquery.
$(document).ready(function() {
$("#container").hover(
function() {
console.log($(".mybox").fadeIn());
$(".mybox").fadeIn();
},
function() {
$(".mybox").fadeOut();
}
);
});
here's a working JSFIDDLE with 2 buttons
It's because you're no longer hovering over the button and instead going to a different element "mybox" so you could rearrange the html structure for it to work by keeping the menu in the button class like so:
<div class="buttons">
<div class="mybutton">
/* Button image here */
<div class="mybox">
<div style="position: absolute;">
Item 1
Item 2
</div>
</div>
</div>
</div>
this should keep the menu active as long as the curser is in there.
I don't recommend this as a UI design pattern for various reasons (one of them being the complexity of implementing it); you could instead consider changing it so that the menu appears when the user clicks.
Having said that, here's a way to do it. Get rid of your existing fadeOut() calls and add this:
$("body").on("mousemove", function(e) {
var $hovered = $(e.target);
var $myButton = $(".myButton");
var $box = $(".myBox");
if ( $hovered.is( $myButton ) ) return;
if ( $hovered.is( $box ) ) return;
if ( $.contains( $box.get(0), $hovered ) ) return;
$box.fadeOut();
});
...and similar for button2. The basic principle is this - whenever the mouse moves, we check whether the mouse is hovering over the button, or the box, or over an element contained in the box (using $.contains()). If not, we hide the box.

Toggle visibility of three or more divs

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>');

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/

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