How to run jQuery function for multiple elements individually? - javascript

I can't make my jQuery function work on individual elements. My function is a slider. When I put one slider to my html, it works fine, without problems. But whenever I try to put a second slider, it doesn't work properly. The first slider controls both of them, then the second slider takes the charge if I click right arrow too much etc.
Here is my jQuery code:
$('.right-arrow').click(function () {
var currentSlide = $('.slide.active');
var nextSlide = currentSlide.next();
currentSlide.fadeOut(300).removeClass('active');
nextSlide.fadeIn(300).addClass('active');
if (nextSlide.length == 0) {
$('.slide').first().fadeIn(300).addClass('active');
}
});
$('.left-arrow').click(function() {
var currentSlide = $('.slide.active');
var prevSlide = currentSlide.prev();
currentSlide.fadeOut(300).removeClass('active');
prevSlide.fadeIn(300).addClass('active');
if (prevSlide.length == 0) {
$('.slide').last().fadeIn(300).addClass('active');
}
});
And this is where I use it:
<style>
.slide {
display:none;
}
.slide.active {
display:block;
}
</style>
<div class="slider-container">
<div id="slider1">
<div class="slide active">#1</div>
<div class="slide">#2</div>
<div class="slide">#3</div>
</div>
<p class="left-arrow"><</p>
<p class="right-arrow">></p>
</div>
<div class="slider-container">
<div id="slider2">
<div class="slide active">#a</div>
<div class="slide">#b</div>
<div class="slide">#c</div>
</div>
<p class="left-arrow"><</p>
<p class="right-arrow">></p>
</div>
Like I said previously, when I click the first slider's right arrow, first slider's #2 and second slider's #b shows up.

You are getting this behavior because of the line
var currentSlide = $('.slide.active');
which selects all elements with the classes slide and active. try replacing that line with something like this:
var currentSlide = $(this).parent().find('.slide.active');
What this is doing is selecting the element the event was fired on $(this). Then getting the parent of that element, then finding the active slide within that element.
EDIT
Here is an example of your first if statement. Once again, you are getting the parent of the element that caused the event, then searching inside that dom element for all of the elements with a class of 'slide'.
As a side note you might want to make $(this) a variable something like var $this = $(this). Then use $this instead of $(this). It's a performance issue that you may or may not be concerned with.
if (nextSlide.length == 0) {
$(this).parent().find('.slide').first().fadeIn(300).addClass('active');
}

As other answers and comments mentioned, you are searching the .slide elements on the whole document. Instead you need to limit the search inside the related .slider-container element. For this purpose, you can use JQuery.closest(). Also, it will be nice to wait the fadeOut animation to finish using the complete callback function before showing the new .slide element. You can take next example as reference of implementation:
$('.right-arrow').click(function()
{
var container = $(this).closest(".slider-container");
var currSlide = container.find('.slide.active');
var nextSlide = currSlide.next(".slide");
if (nextSlide.length === 0)
nextSlide = container.find('.slide:first-child');
currSlide.fadeOut(300, function()
{
$(this).removeClass('active');
nextSlide.fadeIn(300).addClass('active');
});
});
$('.left-arrow').click(function()
{
var container = $(this).closest(".slider-container");
var currSlide = container.find('.slide.active');
var prevSlide = currSlide.prev(".slide");
if (prevSlide.length === 0)
prevSlide = container.find('.slide:last-child');
currSlide.fadeOut(300, function()
{
$(this).removeClass('active');
prevSlide.fadeIn(300).addClass('active');
});
});
.slide {
display:none;
}
.slide.active {
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider-container">
<div id="slider1">
<div class="slide active">#1</div>
<div class="slide">#2</div>
<div class="slide">#3</div>
</div>
<p class="left-arrow"><</p>
<p class="right-arrow">></p>
</div>
<div class="slider-container">
<div id="slider2">
<div class="slide active">#a</div>
<div class="slide">#b</div>
<div class="slide">#c</div>
</div>
<p class="left-arrow"><</p>
<p class="right-arrow">></p>
</div>

Related

Changing multiple divs based on arrows

I have created an input section for users to write their own work. I have multiple divs to the side of this and I'd like to change the divs from a left and right arrow that can be clicked.
$(document).ready(function() {
$('.menubody:nth-child(1)').show('slow');
$('.menubody:nth-child(1)').hide('slow');
$('.fa-caret-right').on({
click: function() {
var i = $('.menubody:visible').index();
var len = $('.menubody').length;
var next;
if (i >= 0) {
if (i == len - 1) {
next = $('.menubody:eq(0)');
} else {
next = $('.menubody:eq(' + (i + 1) + ')');
}
$('.menubody:visible').hide();
$(next).show();
}
}
});
});
EDIT:
I have a working example (see fiddle) that changes and changes the content when 'right' is pressed.
How do I make it so the 'left' div moves the content to previous? And add more than one content area to change?
For an example layout of the usage (not jQuery working), please see here.
Use jQuery's .prev() and .next(). If they return a collection of zero length, use .last() and .first() instead to cycle through your content (not sure that you needed this).
$(function() {
$('.tabs-container div').not(':first-child').hide();
$('#tabs li a').click(function() {
var $clickedLink = $(this),
$visible = $('.tabs-container div:visible');
$visible.each(function(){
var $this = $(this),
$parentContainer = $this.parents('.tabs-container').eq(0),
$toShow;
if( $clickedLink.is('.prev') ){
$toShow = $this.prev('div').length ? $this.prev('div') : $('div', $parentContainer).last();
} else {
$toShow = $this.next('div').length ? $this.next('div') : $('div', $parentContainer).first();
}
$this.hide();
$toShow.show();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul id="tabs">
<li>Left Arrrow
</li>
<li>Right Arrow
</li>
</ul>
<div class="tabs-container">
<div id="content1">Content for link 1. Should display only when Link 1 is clicked.</div>
<div id="content2">Content for link 2. Should display only when Link 2 is clicked.</div>
<div id="content3">Content for link 3. Should display only when Link 3 is clicked.</div>
<div id="content4">Content for link 4. Should display only when Link 4 is clicked.</div>
</div>
<p>Unrelated text is here. Text in this area is static and should display at all times.</p>
<div class="tabs-container">
<div id="content1-2">Additional content for link 1. Should display only when Link 1 is clicked.</div>
<div id="content2-2">Additional content for link 2. Should display only when Link 2 is clicked.</div>
</div>
<p>More unrelated text</p>
<div class="tabs-container">
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
</div>
I think you should use the nth-child() jQuery selector here. Simply increment the value of n every time the button right is clicked and decrease the value of n every time the left arrow is clicked.
$('#left-arrow').on('click', function(){
var i++;
$('main-div:nth-child(i-1)').hide();
$('main-div:nth-child(i)').show();
})
Here's a link to read more : W3 Schools :nth-child() selector

How can I separate these divs in the javascript?

I have this div scrolling script:
$(document).ready(function () {
$('.tab-box').each(function () {
var top = 0;
var $tabbox = $(this);
var height = $tabbox.height();
$(this).find('.tab').each(function () {
var shift = top;
$(this).click(function () {
$tabbox.find('.items').animate({
marginTop: shift + 'px'
});
$tabbox.find('.tab').removeClass('active');
$(this).addClass('active');
});
top -= height;
});
$(this).find('.tab:eq(0)').addClass('active');
});
});
If I understand it correctly it gets every divs working only within the div "tab-box".
http://jsfiddle.net/9SfEH/5/
What I want to change is that I separate the "tabs" from the main tab-box div, but make them still controll the "items".
http://jsfiddle.net/w65Dn/1/
I was trying for a simple solution buuut couldn't come up with one by myself.
Thanks everyone in advance :)
The problem was that in the original code, it was looking for the tab clickables using $(this).find(".tab"), but the .tabs were no longer inside of the .tab-box. So, if you just search globally, with $(".tab"), it works.
Note that you can no longer have more than one tab box, because it is searching globally for the .tabs. You could use something like javaCity's solution (i.e. wrapping everything in another div) to fix this.
You were looking for .tabs inside the tab-box which does not exist. So how about creating a div outside of .tabs which also encloses tab-box?
http://jsfiddle.net/3D8we/
HTML:
<div class="enclosingDiv">
<div class="tabs">
<div class="tab">1</div>
<div class="tab">2</div>
<div class="tab">3</div>
</div>
<div class="tab-box">
<div class="items">
<div class="item" style="background: #cbe86b;"></div>
<div class="item" style="background: #f2e9e1;"></div>
<div class="item" style="background: #1c140d;"> </div>
</div>
</div>
</div>
JS:
$(document).ready(function () {
$('.tab-box').each(function () {
var top = 0;
var $tabbox = $(this);
var height = $tabbox.height();
$('.enclosingDiv').find('.tab').each(function () {
var shift = top;
$(this).click(function () {
$tabbox.find('.items').animate({
marginTop: shift + 'px'
});
$tabbox.find('.tab').removeClass('active');
$(this).addClass('active');
});
top -= height;
});
$(this).find('.tab:eq(0)').addClass('active');
});
});
On line 7, change the selector from this to .tabs
$(this).find('.tab') becomes $(.tabs).find('.tab')
as seen here: jsfiddle example

Select next element carousel

I have a list of DIVs, and I want every X second using setTimeout to take the next div and set the display to block, and for the other ones to none, how can I do that? Can someone please give me an example?
How can I make it to be infinite, when reaches the last one to start from the first one again.
I know this is a kind of carousel, but I want too see how it's done.
There are many ways to do this, but here's one way: http://jsfiddle.net/jfriend00/Yr3NV/
HTML:
<div id="container">
<div class="item active">1111</div>
<div class="item">2222</div>
<div class="item">3333</div>
<div class="item">4444</div>
<div class="item">5555</div>
<div class="item">6666</div>
<div class="item">7777</div>
</div>
Code:
setInterval(function() {
var next = $("#container .active").removeClass("active").next();
if (next.length == 0) {
next = $("#container .item:first");
}
next.addClass("active");
}, 1000);
CSS:
.item {display: none;}
.item.active {display: block;}
Using the method of adding/removing a class gives you a little more style control via CSS rather than coding the style into your javascript and avoids the use of any global or closure variables to keep the state.
var divs = $('#container').find('div'),
index = 0;
setInterval(function() {
if (!divs[index]) index = 0;
divs.hide();
divs[index++].style.display = 'block';
}, 1000); // fires every 1 second
All the usual disclaimers about global scope being a bad idea, but this should give you what you want.
$("#list div").hide();
var current = $("#list div").first().show();
setInterval(function() {
current.hide();
current = current.next().length > 0 ? current.next() : $("#list div").first();
current.show();
},2000);
<div id="list">
<div>1</div>
<div>22</div>
<div>333</div>
<div>4444</div>
</div>
Can be seen working here:
http://jsfiddle.net/KenwV/
Here's an implementation with setTimeout: http://jsfiddle.net/imsky/EBpTw/
Given a UL with id of "list" and LIs inside:
$(function() {
$("#list li:gt(0)").hide();
function showNextBlock() {
var currentBlock = $("#list li:visible");
if (currentBlock.index() == $("#list li").length - 1) {
currentBlock.hide().parent().find("li:first").show()
}
else {
currentBlock.hide().next("li").show();
}
setTimeout(showNextBlock,1000);
}
setTimeout(showNextBlock,1000);
});
DIV LOOP DEMO
var i=0, len=$('#parent div').length;
(function loop(){
$('#parent div').eq(i++%len).fadeTo(700,1).siblings().fadeTo(700,0,loop);
})();
HTML example:
<div id="parent">
<div class="children ch1">I'm DIV 1</div>
<div class="children ch2">I'm DIV 2</div>
<div class="children ch3">I'm DIV 3</div>
<div class="children ch4">I'm DIV 4</div>
</div>
CSS basic setup:
.children{
position:absolute;
}
And here is one with a mouseover pause :
DEMO with mouseover pause
function cycleDivs(base)
{
var next = ($(base).next('div').css('display') == 'none')? $(base).next('div') : $('div:first');
$(base).hide();
$(next).show();
window.setTimeout(function(){cycleDivs(next);}, 1000)
}
window.setTimeout(function(){cycleDivs($('div:first'));}, 1000);
Here's a working example: http://jsfiddle.net/8hfBd/

jQuery fadein/out

I have a div with several images. I need to only display 6 at a time. I then need to fade out current six and fade in next 6 in the list.
I have this wrapped in a setInterval function. Is this possible?
So far, I’ve got:
var hiddenElements = $('.logos div.logo:gt(5)');
hiddenElements.hide();
setInterval(function() {
// …
}, 2000);
"logo" is the class of the divs that need to fade. They all have CSS background images (hence no img tags).
This is very straight approach. Just for fun. But you should optimize your html. Wrap every 6 images in one container and then toggle them - it will more clean and nature solution.
sketch: http://jsfiddle.net/fl00r/HSGF3/4/
<div class='hidden'>1</div>
<div class='hidden'>2</div>
<div class='hidden'>3</div>
<div class='hidden'>4</div>
<div class='hidden'>5</div>
<div class='hidden'>6</div>
<div class='hidden'>7</div>
<div class='hidden'>8</div>
<div class='hidden'>9</div>
<div class='hidden'>10</div>
<div class='hidden'>11</div>
<div class='hidden'>12</div>
<div class='hidden'>13</div>
<div class='hidden'>14</div>
<div class='hidden'>15</div>
<div class='hidden'>16</div>
<script>
$(function(){
fadeByEachSlice(".hidden",6)
})
function fadeByEachSlice(object, step){
var i = 0;
objects = $(object)
function nextSlice(){
if(i%step == 0){
if( i <= objects.length ){
slice = objects.slice(i, step+i);
fadeSlice(slice)
}
}
}
function fadeSlice(slice){
$(slice).fadeIn().delay(1000).fadeOut("fast", function(){
i+=1; nextSlice();
})
}
nextSlice()
}
</script>
you can use jQuery delay function to show 6 images for a while and then fadeout them and fadein next six.

JS: Hiding DIV based on another DIVs content

I am looking to hide a number of DIVs based upon the specific text of another DIV. My Javascript (below) isn't working.
The HTML:
<div id="LEGEND">abAB</div>
<div id="small-a"></div>
<div id="small-b"></div>
<div id="big-a"></div>
<div id="big-b"></div>
If the LEGEND DIV contains the text a, then I want it to show only DIV small-a.
If the LEGEND DIV contains the text bA, then I want it to show only DIV small-b and big-a.
The Javascript:
<script>
window.onload = function ShowHide{
if (document.getElementById('LEGEND').indexOf("a") > 0){
document.getElementById('small-a').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("b") > 0){
document.getElementById('small-b').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("A") > 0){
document.getElementById('big-a').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("a") > 0){
document.getElementById('big-b').style.display = 'block';}
</script>
You are forgetting a couple of things.
A function declaration should be like this
function functionName(args) {
}
You have to hide the divs using style.display = "none"
Example:
<div id="LEGEND">abB</div>
<div id="small-a" style="display: none;">This is small-a</div>
<div id="small-b" style="display: none;">This is small-b</div>
<div id="big-a" style="display: none;">This is big-a</div>
<div id="big-b" style="display: none;">This is big-b</div>
<script>
function showElement(id) {
document.getElementById(id).style.display = "block";
}
window.onload = function ShowHide() {
var legend = document.getElementById("LEGEND").innerHTML;
if(legend.indexOf("a") != -1) showElement("small-a");
if(legend.indexOf("b") != -1) showElement("small-b");
if(legend.indexOf("A") != -1) showElement("big-a");
if(legend.indexOf("B") != -1) showElement("big-b");
}
</script>
The problem is that your code changes the other div elements to block-level elements when div is already a block-level element. You need to set them not to display initially using CSS and then reveal them in the JavaScript.
Try this instead:
<div id="LEGEND">abAB</div>
<div id="small-a" style="display: none;"></div>
<div id="small-b" style="display: none;"></div>
<div id="big-a" style="display: none;"></div>
<div id="big-b" style="display: none;"></div>
<script type="text/javascript">
window.onload = function() {
if (document.getElementById('LEGEND').indexOf('a') > 0) {
document.getElementById('small-a').style.display = 'block';
...
// etc.
}
}
</script>
First, try making sure the window.onload is being called:
window.addEventListener('load', ShowHide, false);
function ShowHide()
{...
Second, you should be looking at the InnerHTML of the element:
if (document.getElementById('LEGEND').innerHTML.match("a") == "a"){...
Third, each if statement should also contain an else (replace divName with real div names):
else {
document.getElementById('divName').style.display = 'none'}
Hope that helps!
~md5sum~
EDIT:
Also, I'm not 100% sure on this, but I believe that the syntax:
window.onload = function ShowHide{
will completely fail. I think that the syntax should be:
window.onload = function(){
If me, I will do like this. you dont need to touch HTML part, everything is done in javascript.
you can extend it to CDEFGH...
and you don't need to set <div id="small-X" style="display: none;"> for each tags too. :-)
<body>
<script>
window.onload=function(){
x=document.getElementsByTagName("div");
//first hide everything with small- or big-
for(i in x)
if(/small-|big-/.test(x[i].id))
x[i].style.display="none";
//then turn on each tags based on LEGEND
x= document.getElementById("LEGEND").innerHTML;
for(i=0;i<x.length;i++)
document.getElementById((x[i]<='Z'?'big-':'small-')+x[i].toLowerCase()).style.display='block';
}
</script>
<div id="LEGEND">aAB</div>
<div id="small-a">a</div>
<div id="small-b">b</div>
<div id="big-a">A</div>
<div id="big-b">B</div>
</body>
You need to set the style.display property to none.

Categories