Get next element after the active - javascript

how to get the next dt after the dt with class active?
my HTML::
<dt class="active">...</dt>
<dd>...</dd>
<dt>...</dt>
<dd>...</dd>
<dt>...</dt>
<dd>...</dd>
look, i have this function:
function slideShow() {
var active = $('dl dt.active',ctx);
active.next('dt').addClass('active');
};
window.setInterval(slideShow, 5000);
should be simple. every sec the DOM show where the active dt is and set the next dt of this active.

One possible solution is
$('.active').nextUntil('dt').last().next()
Demo: Fiddle
For the slide show
var $dts = $('dl dt');
function slideShow() {
var index = $dts.index($dts.filter('.active').removeClass('active')) + 1;
var active = $dts.eq(index > 0 && index < $dts.length ? index : 0);
active.addClass('active');
};
window.setInterval(slideShow, 1000);
Demo: Fiddle

Its not so simple, you can use the next sibling selector ~ in combination with eq() to select the element:
$(".active ~dt:eq(0)")
JS Fiddle: http://jsfiddle.net/hsAA7/

Related

jQuery toggle Class on multiple Elements with interval

I've created this little fancy jQuery Snippet to toggle the class of an element in an interval:
setInterval(function(){$('.grid-item .slide-image').toggleClass('active')}, 800);
The script works fine! Now I got multiple elements with the base-class .slide-image in the wrapper .grid-item.
<div class="grid-item">
<div class="slide-image"><img src="http://www.placehold.it/500x500/233953"></div>
<div class="slide-image"><img src="http://www.placehold.it/500x500/03144b"></div>
<div class="slide-image"><img src="http://www.placehold.it/500x500/030a4b"></div>
</div>
Is there a way to rewrite the snippet so the second .slide-image gets the class .active after the first one? Then the third element and so on...
The Problem: The amout of .slide-image-elements is no defined. In some cases there are two of them, in another there are four elements.
Check out my CodePen!
Try this
var slides = $('.grid-item .slide-image'), // cache slides
counter = 0; // global counter
setInterval(function(){
slides.removeClass('active'); // remove active class
slides.eq(counter).addClass('active'); // add active class
counter++;
if (counter == slides.length) counter = 0; // reset counter after last slide
}, 800);
Updated CodePen
You can check if current active element id last or not. if it is, then show first element in set else show next sibling element:
$(function(){
var slides = $('.grid-item .slide-image');
setInterval(function(){
var currentactive = $('.active');
var _target = currentactive.is(':last-child') ? slides.first() : currentactive.next();
slides.removeClass('active')
_target.addClass('active')
}, 800);
});
Working Demo

How to reduce 180 lines of code down to 20 in Javascript?

I have a lot of click handler functions which are almost (textually and functionally) identical. I've got a menu with maybe 10 items in it; when I click on an item, the click handler simply makes one div visible, and the other 9 div's hidden. Maintaining this is difficult, and I just know there's got to be a smart and/or incomprehensible way to reduce code bloat here. Any ideas how? jQuery is Ok. The code at the moment is:
// repeat this function 10 times, once for each menu item
$(function() {
$('#menuItem0').click(function(e) {
// set 9 divs hidden, 1 visble
setItem1DivVisible(false);
// ...repeat for 2 through 9, and then
setItem0DivVisible(true);
});
});
// repeat this function 10 times, once for each div
function setItem0DivVisible(on) {
var ele = document.getElementById("Item0Div");
ele.style.display = on? "block" : "none";
}
Create 10 div with a class for marking
<div id="id1" class="Testing">....</div>
<div id="id2" class="Testing">....</div>
<div id="id3" class="Testing">....</div>
and apply the code
$('.Testing').each(function() {
$(this).click(function() {
$('.Testing').css('display', 'none');
$(this).css('display', 'block');
}
}
$(document).ready(function (){
$("div").click(function(){
// I am using background-color here, because if I use display:none; I won't
// be able to show the effect; they will all disappear
$(this).css("background-color","red");
$(this).siblings().css("background-color", "none");
});
});
Use .siblings() and it makes everything easy. Use it for your menu items with appropriate IDs. This works without any for loops or extra classes/markup in your code. And will work even if you add more divs.
Demo
Fiddle - http://jsfiddle.net/9XSJW/1/
It's hard to know without an example of the html. Assuming that there is no way to traverse from the menuItem to ItemDiv - you could use .index and .eq to match up the elements based on the order they match with the selector.
var $menuItems = $("#menuItem0, #menuItem1, #menuItem2, ...");
var $divs = $("#Item0Div, #Item1Div, #Item2Div, ...");
$menuItems.click(function(){
var idx = $(this).index();
// hide all the divs
$divs.hide()
// show the one matching the index
.eq(idx).show();
})
Try
function addClick(i) {
$('#menuItem'+i).click(function(e) {
// set nine divs hidden, 1 visble
for( var j = 0; j < 10; ++j ) {
var ele = document.getElementById("Item"+j+"Div");
ele.style.display = (i == j ? "block" : "none");
}
});
}
// One click function for all menuItem/n/ elements
$('[id^="menuItem"]').on('click', function() {
var id = this.id; // Get the ID of the clicked element
$('[id^="Item"][id$="Div"]').hide(); // Hide all Item/n/Div elements
$('#Item' + id + 'Div').show(); // Show Item/n/Div related to clicked element
});
Obviously this would be much more logical if you were using classes instead:
<elem class="menuItem" data-rel="ItemDiv-1">...</elem>
...
<elem class="ItemDiv" id="ItemDiv-1">...</elem>
$('.menuItem').on('click', function() {
var rel = $(this).data('rel'); // Get related ItemDiv ID
$('.ItemDiv').hide(); // Hide all ItemDiv elements
$('#' + rel).show(); // Show ItemDiv related to clicked element
});
Save the relevant Id's in an array - ["Item0Div", "Item1Div", ...]
Create a generic setItemDivVisible method:
function setItemDivVisible(visible, id) {
var ele = document.getElementById(id);
ele.style.display = visible ? "block" : "none";
}
And set your click handler method to be:
function(e) {
var arrayLength = myStringArray.length;
for (var i = 0; i < idsArray.length; i++) {
setItemDivVisible(idsArray[i] === this.id, idsArray[i]);
}
}
I think this will do the trick

fadeIn li one by one

I have a list of some item, i want fadeIn element one by one, means if first element complete fadeIn then next element fadeIn and so on, in my given code what going wrong i dont know, please help me..
HTML
<ul id="ulfade"><li>ABC</li><li>ABC</li><li>ABC</li><li>ABC</li></ul>
JS
var i=0;
$('#ulfade li:nth-child(' + i + ')').fadeIn(500, function () {
$('#ulfade li:nth-child(' + (++i) + ')').fadeIn('slow');
});
jsFiddle: http://jsfiddle.net/subhash9/suUHD/2/
You can solve it like this:
$('#ulfade li').each(function(key, value) {
$(value).delay(key * 500).fadeIn(500);
});
Demo
Try before buy
Edit
As you changed your fiddle, here's a solution that works when hovering some other element:
$('#divFade').mouseover(function() {
$('#ulfade li').each(function(key, value) {
$(value).delay(key * 500).fadeIn(500);
});
$(this).unbind();
});
Demo 2
Try before buy
You can also do it without using delay by doing the following:
$('#divFade').mouseover(function() {
var i = 0;
var list = $('#ulfade li');
(function displayLI() {
list.eq(i++).fadeIn(500, displayLI);
})();
$(this).unbind();
});
This uses the completion callback to iteratively fade in the next item in the list.
Demo

How to change .index()'s default index of 0 to 1 for the first element

I am using .index() to get the position of the element. So by default it returns 0 for first one. Is there is a way to set default to 1 so the returned index would be 1,2,3... instead of 0,1,2...?
<div class="tabs">
1
2
3
</div>
and the jQuery:
$(function(){
$('.tabs a').click(function(e){
var index = $('.tabs a').index(this);
console.log(index);
e.preventDefault();
});
});
You can't change the default, but you could add it manually
var index = $('.tabs a').index(this) + 1;
If that's not good enough, you could create a plugin that would return the value you want.
(function($){
$.fn.myIndex = function(x) {
return $(this).index(x) + 1;
};
})(jQuery);
So you can then use .myIndex and get jQuery's index with 1 added to it.
Live example

Twitter Bootstrap Carousel - access current index

How do I get the current index from the carousel?
In this case I am using an unordered list. I know I could search through the list items to find the one with the 'active' CSS class, but I want to know if I can ask the carousel object directly.
Additional: being able to access the target index (on 'slide' event) would be handy also. Again, I can do this by searching with:
var idx = $('.carousel-inner li.active').index();
...and then adding/subtracting based on direction, but I am hoping for something cleaner.
Instead of adding and subtracting from the current slide, try this on the 'slide' event:
$('.carousel').on('slide',function(e){
var slideFrom = $(this).find('.active').index();
var slideTo = $(e.relatedTarget).index();
console.log(slideFrom+' => '+slideTo);
});
This worked for me (Bootstrap 3)
$("#myCarousel").on('slide.bs.carousel', function(evt) {
console.debug("slide transition started")
console.debug('current slide = ', $(this).find('.active').index())
console.debug('next slide = ', $(evt.relatedTarget).index())
})
It appears Bootstrap 4 finally has the native implementation of this.
https://github.com/twbs/bootstrap/pull/21668
$('#myCarousel').on('slide.bs.carousel', function(e){
e.direction // The direction in which the carousel is sliding (either "left" or "right").
e.relatedTarget // The DOM element that is being slid into place as the active item.
e.from // The index of the current item.
e.to // The index of the next item.
});
Nope, there is no way to access index or direction.
See here
// EDIT
Bootstrap changed repos, new link
For bootstrap 3 it's
$('#myCarousel').on('slide.bs.carousel', function (e) {
var active = $(e.target).find('.carousel-inner > .item.active');
var from = active.index();
var next = $(e.relatedTarget);
var to = next.index();
console.log(from + ' => ' + to);
})
from https://github.com/twbs/bootstrap/pull/2404#issuecomment-22362366
$(".active", e.target).index() works. Where e from:
carousel.on("slid", function (e) {
$(".active", e.target).index();
});
Found on: https://github.com/twitter/bootstrap/pull/2404#issuecomment-4589229
I'm doing it like that, that works sort of very well ;)
var slider = $("#slider-wrapper")
.carousel({
interval: 4000
})
.bind('slid', function() {
var index = $(this).find(".active").index();
$(this).find("a").removeClass('pager-active').eq(index).addClass('pager-active');
});
$("#slider-wrapper a").click(function(e){
var index = $(this).index();
slider.carousel(index);
e.preventDefault();
});
I was able to access the slide index using a jquery function from the bootstrap documentation.
$('#carousel').on('slide.bs.carousel', function(event) {
alert(event.from);
// You can use use 'event.from' in whatever way works best for you here
}
.from on the event will give you the slide where the slide instance occurs. .to will give you the slide where the slide instance is going to. Using slide.bs.carousel will execute the function before the slide animation, slid.bs.carousel will execute the function after the slide animation but the returned slide number will be the same.
There's a few other properties that the slide and slid events give you access to, I recommend checking them out on the carousel documentation page.
Note: I am using bootstrap 4.3.1.
Here's what I came up with after reading fat's comment in #Quelltextfabrik's answer.
var carousel = $("#myCarousel");
carousel.on("slid", function () {
var all = carousel.find('.item'),
active = carousel.find('.active'),
slidTo = all.index(active);
console.log("Slid - Slid To: " + slidTo);
});
carousel.on("slide", function () {
var all = carousel.find('.item'),
active = carousel.find('.active'),
slidFrom = all.index(active);
console.log("Slide - Slid From: " + slidFrom);
});

Categories

Resources