jQuery Content Slider Stopped working after Click - javascript

function nextSlideFunc() {
var currentSlide = $(".slide.active-slide");
var currentSlideIndex = $(".slide.active-slide").index();
var nextSlideIndex = currentSlideIndex + 1;
var nextSlide = $(".slide").eq(nextSlideIndex);
$("#nextBtn").on("click", function(e) {
e.preventDefault();
currentSlide.removeClass("active-slide");
if(nextSlideIndex === $(".slide").last().index() + 1) {
//stay at last slide when reached.
$(".slide").eq(nextSlideIndex - 1).addClass("active-slide");
} else {
nextSlide.addClass("active-slide");
}
});
}
After I clicked on the next button, the slide goes to the next slide which is what I want, but when I continue to click, it just stopped going forward.
I checked my HTML in the dev tool, it has the class name "active-slide" on one of the slides which fulfills the condition, but I'm not sure why it's not working.
As for the previous button, it's not removing class "active-slide" like it's supposed to, any idea why this is happening?

You have to set your variables inside the listener of your click event:
https://codepen.io/anon/pen/OxMxwd
$("#prevBtn").on("click", function(e) {
var currentSlide = $(".slide.active-slide");
var currentSlideIndex = $(".slide.active-slide").index();
var prevSlideIndex = currentSlideIndex - 1;
var prevSlide = $(".slide").eq(prevSlideIndex);
}
That way you will calculate your index and next index every time you click the button. The way you did it, is calculating it once and reusing it over and over again, so you will do the same thing on the same index over and over again.

Related

why add the class next left when I should add the active class in the boostrap carousel

What I want to do is that when my question has a timer and the user next, that question disappears and I can not answer it.
Code:
var timer = $(".active").attr('data-timer');
if (timer == undefined) {
var $carousel = $('#carousel');
var NextElement = $carousel.next('.item').first();
NextElement.addClass('active');
$('.timer').remove();
} else {
var $carousel = $('#carousel');
var ActiveElement = $carousel.find('.item.active');
ActiveElement.remove();
var NextElement = $carousel.next('.item');
NextElement.addClass('active');
$('.timer').remove();
}
It does everything, except that when it enters the else instead of adding the active in my carousel it adds the class next left.
Instead of this class being added, it should be active, so when it re-enters the if the slide does not work anymore. Even add the following:
var NextElement = $carousel.next('.item').first();
It's the .first
Just use var NextElement = $carousel.next('.item'), next only returns one element https://api.jquery.com/next/

Adding Next and Previous Buttons to Bootstrap Targeting Link IDs

I am attempting to add next/prev and then swipe events to a bootstrap modal image gallery. The thumbnails are displayed in a grid so when I try closest(), siblings(), and next() I am only able to go to the images below and above in the same column and not the other columns in the grid.
Each thumbnail has an id with the images ID in the database. ie:
<a class="image-gallery-item" id="img-1002" href="#showImageModal" data-toggle="modal" onclick="..."><img src="..." /></a>
<a class="image-gallery-item" id="img-4664" href="#showImageModal" data-toggle="modal" onclick="..."><img src="..." /></a>
Every link passes the images src, caption, and ID to a function which changes out the info displayed the modal. All that works fine, I just can't seem to get next/prev working when trying to trigger the next item.
Ideally, instead of using next() and closest() and sibling() methods, I would LIKE to just target the ID greater than the current id for first next and lesser than the current ID for the first previous and trigger a click if the element exists.
Thanks.
UPDATE
Per #Ersian's suggestion, I created an array and cycle thru the images by index. They're still going by column but at least they're moving to the next column after. This will present a little confusion for users, I feel, who will expect the images to display left to right before going to the next row of square thumbnails.
$('.image-gallery-item').modal('hide');
setTimeout(function () {
var thisIMG = $("#imgid").html();
var imgs = document.getElementsByClassName("image-gallery-item");
var $imgvalues = Array.prototype.map.call(imgs, function (el) {
return el.id;
});
index = $imgvalues.indexOf(thisIMG);
if (index >= 0 && index < $imgvalues.length - 1)
nextItem = $imgvalues[index + 1];
$('#' + nextItem).trigger('click');
}, 1000);
UPDATE - WORKING CODE
Found the solution by adding sort to the array and then looped the next/prev if hitting the end or start of items with the class image-gallery-item. I'll post the working code as an answer in case anyone else finds this question and wants to make a bootstrap modal image gallery with gridalicious, isotope, or masonry layouts with columns.
Keep in mind you will need to add buttons with show-next-image and show-previous-image classes to your modal. After that, the following code will let you cycle thru images with the class image-gallery-item.
$('#show-next-image, #show-previous-image').click(function () {
if ($(this).attr('id') == 'show-previous-image') {
$('#showImageModal').modal('hide');
setTimeout(function () {
var thisIMG = $("#imgid").html();
var imgs = document.getElementsByClassName("image-gallery-item");
var $imgvalues = Array.prototype.map.call(imgs, function (el) {
return el.id;
});
var lastIMG = $('.image-gallery-item').length;
$imgvalues.sort();
index = $imgvalues.indexOf(thisIMG);
if (index <= lastIMG - 2) {
nextItem = $imgvalues[index + 1];
} else {
nextItem = $imgvalues[0];
}
$('#' + nextItem).trigger('click');
}, 1000);
} else {
$('#showImageModal').modal('hide');
setTimeout(function () {
var thisIMG = $("#imgid").html();
var imgs = document.getElementsByClassName("image-gallery-item");
var $imgvalues = Array.prototype.map.call(imgs, function (el) {
return el.id;
});
var lastIMG = $('.image-gallery-item').length;
$imgvalues.sort();
index = $imgvalues.indexOf(thisIMG);
if (index >= 1) {
nextItem = $imgvalues[index - 1];
} else {
nextItem = $imgvalues[lastIMG - 1];
}
$('#' + nextItem).trigger('click');
}, 1000);
}
});

Custom slider issue

I have written a custom slider with object-oriented javascript as seen below. I have included the module in a fiddle here https://jsfiddle.net/5z29xhzg/7/. After sliding left or right, the slides are cloned and appended accordingly so that the user can loop through the slider as much as wanted. There is a separate function for controlling the active tab. When used separately, the tabs and slider work perfectly, but I am having an issue when the two are used in conjuction. For instance, clicking 'blue apron' and then clicking the left slide button (which should take you to the 'dave & busters' slide) takes you to the bliss slide. Or clicking the last slide using the tabs and then clicking the next button does not show anything. Can someone point out the flaw in the object that I have written. Any help is much appreciated!
GiftSlider = {
prev: '.slider-container .prev',
next: '.slider-container .next',
slide: '.slide',
slidesContainer: '#slides',
navLink: '.gift-nav li a',
init: function() {
// Initialize nextSlide function when clicking right arrow
$(this.next).click(this.nextSlide.bind(this));
$(this.next).click(this.activeTabs.bind(this));
// Initialize prevSlide function when clicking left arrow
$(this.prev).click(this.prevSlide.bind(this));
$(this.prev).click(this.activeTabs.bind(this));
// Initialize toggleSlides and activeTab functions when clicking nav links
$(this.navLink).click(this.toggleSlides.bind(this));
$(this.navLink).click(this.activeTabs.bind(this));
},
nextSlide: function(e) {
// Prevent default anchor click
e.preventDefault();
// Set the current slide
var currentSlide = $('.slide.current');
// Set the next slide
var nextSlide = $('.slide.current').next();
// remove the current class from the current slide
currentSlide.removeClass("current");
// Move the current slide to the end so we can cycle through
currentSlide.clone().appendTo(this.slidesContainer);
// remove the last slide so there is not two instances
currentSlide.remove();
// Add current class to next slide to display it
nextSlide.addClass("current");
},
prevSlide: function(e) {
// Prevent defaulct anchor click
e.preventDefault();
// Set the current slide
var currentSlide = $('.slide.current');
// Set the last slide
var lastSlide = $('.slide').last();
// remove the current class from the current slide
currentSlide.removeClass("current");
// Move the last slide to the beginning so we can cycle through
lastSlide.clone().prependTo(this.slidesContainer);
// remove the last slide so there is not two instances
lastSlide.remove();
// Add current class to new first slide
$('.slide').first().addClass("current");
},
toggleSlides: function(e) {
// Prevent defaulct anchor click
e.preventDefault();
var itemData = e.currentTarget.dataset.index;
var currentSlide = $('.slide.current');
currentSlide.removeClass("current");
newSlide = $('#slide-' + itemData);
// currentSlide.clone().appendTo(this.slidesContainer);
newSlide.addClass("current");
// console.log(newSlide);
},
activeTabs: function() {
// *** This could be much simpler if we didnt need to match the slider buttons
// *** up with nav tabs. Because I need to track the slider as well, I have
// *** made this its own function to be used in both instances
// get the active slide
var activeSlide = $('.slide').filter(':visible');
// get the active slide's id
var currentId = activeSlide.attr('id');
// grab just the number from the active slide's id
var currentNum = currentId.slice(-1);
// remove any active gift-nav links
$(this.navLink).removeClass("active");
// get the current tab by matching it to the current slide's id
var currentTab = $('.gift-nav li a[data-index="' + currentNum + '"]');
// make that active
currentTab.addClass("active");
}
}
$(document).ready(function(){
// Init our objects
GiftSlider.init();
});
The bug seems to be in toggleSlides.
EDIT: The following doesn't work
When the page loads, currentSlide is slide 1. Now say you click the 3rd tab. At this point, you need to move the slide before the 3rd tab i.e. the 2nd tab to the end. When you say currentSlide.clone().appendTo(this.slidesContainer);, you are instead moving the first slide to the end. Therefore no matter which tab you clicked, when you click the previous button it was going to the first slide.
If instead you do newSlide.prev().clone().appendTo(this.slidesContainer); the code seems to work fine.
toggleSlides: function(e) {
// Prevent defaulct anchor click
e.preventDefault();
var itemData = e.currentTarget.dataset.index;
var currentSlide = $('.slide.current');
currentSlide.removeClass("current");
newSlide = $('#slide-' + itemData);
//currentSlide.clone().appendTo(this.slidesContainer);
newSlide.prev().clone().appendTo(this.slidesContainer);
newSlide.addClass("current");
//console.log("In toggle slide: "+newSlide.next().attr("id"));
//console.log("In toggle slide: "+newSlide.prev().attr("id"));
//console.log("In toggle slide: "+$('.slide.current').next().attr("id"));
},
This seems to work. Check it out at https://jsfiddle.net/rfgnm992/1/. Your nextSlide and previousSlide seems to keep the current slide at the beginning. toggleSlides wasn't doing that.
toggleSlides: function(e) {
// Prevent defaulct anchor click
e.preventDefault();
var itemData = e.currentTarget.dataset.index;
var currentSlide = $('.slide.current');
currentSlide.removeClass("current");
newSlide = $('#slide-' + itemData);
//keep new slide at the beginning and move the preceding slides to the end
newSlide.nextAll().addBack().prependTo(this.slidesContainer);
//console.log("NewSlide.next: "+newSlide.next().attr('id') + "NewSlide.next.next: "+newSlide.next().next().attr('id')+"newSlide.next.next.next: "+newSlide.next().next().next().attr('id'));
//currentSlide.clone().appendTo(this.slidesContainer);
newSlide.addClass("current");
// console.log(newSlide);
},
sorry I got back a bit later than expected. Took a look there. Think you're over-complicating things with the whole append/prepend/cloning thing.
I got it working, but there's a minor bug in it still. It cycles grand, forward and back and the correct links highlight, however when you click on a random link it doesn't immediately highlight, but when you click the next/prev buttons, the relevant links from the chosen image highlight. It's certainly an advance!!! I'm sure I could roll it out with another look, but its 2am here, and I've already been looking at it for an hour and a half!
Here's a fiddle and a snippet (just js cos my msg was too long - I just took out the paragraph at the end of the content, no css changes)
GiftSlider = {
prev: '.slider-container .prev',
next: '.slider-container .next',
slide: '.slide',
slidesContainer: '#slides',
navLink: '.gift-nav li a',
init: function() {
// Initialize nextSlide function when clicking right arrow
$(this.next).click(this.nextSlide.bind(this));
$(this.next).click(this.activeTabs.bind(this));
// Initialize prevSlide function when clicking left arrow
$(this.prev).click(this.prevSlide.bind(this));
$(this.prev).click(this.activeTabs.bind(this));
// Initialize toggleSlides and activeTab functions when clicking nav links
$(this.navLink).click(this.activeTabs.bind(this));
$(this.navLink).click(this.toggleSlides.bind(this));
},
nextSlide: function(e) {
// Prevent default anchor click
e.preventDefault();
// Set the current slide
var currentSlide = $('.slide.current');
// Set the next slide
var currentId = currentSlide.attr('id');
var currNum = (currentId.slice(-1));
var nextNum;
var increment = 1;
if (currNum == 4){
nextNum = 1;
}
else
{
nextNum = parseInt(currNum) + parseInt(increment) ;
}
var nextSlide = $('#slide-' + nextNum);
// remove the current class from the current slide
currentSlide.removeClass("current");
// Add current class to next slide to display it
nextSlide.addClass("current");
// remove the last slide so there is not two instances
},
prevSlide: function(e) {
// Prevent default anchor click
e.preventDefault();
// Set the current slide
var currentSlide = $('.slide.current');
// Set the last slide
var currentId = currentSlide.attr('id');
var currNum = (currentId.slice(-1));
var prevNum;
var decrement =1;
if (currNum == 1){
prevNum = 4;
}
else
{
prevNum = parseInt(currNum) - parseInt(decrement) ;
}
var prevSlide = $('#slide-' + prevNum);
// Move the last slide to the beginning so we can cycle through
currentSlide.removeClass("current");
// Add current class to new first slide
prevSlide.addClass("current");
},
toggleSlides: function(e) {
// Prevent defaulct anchor click
e.preventDefault();
var itemData = e.currentTarget.dataset.index;
var currentSlide = $('.slide.current');
currentSlide.removeClass("current");
newSlide = $('#slide-' + itemData);
newSlide.addClass("current");
},
activeTabs: function() {
var activeSlide = $('.slide').filter('.current');
// get the active slide's id
var currentId = activeSlide.attr('id');
// grab just the number from the active slide's id
var currentNum = currentId.slice(-1);
// remove any active gift-nav links
$(this.navLink).removeClass("active");
// get the current tab by matching it to the current slide's id
var currentTab = $('.gift-nav li a[data-index="'+ currentNum + '"]');
// make that active
currentTab.addClass("active");
}
}
$(document).ready(function(){
// Init our objects
GiftSlider.init();
});

Jquery not working on Drupal platform but works fine locally

I have the following jQuery or a carousel which I have pieced together.
The jQuery works fine locally - but when uploaded to a Drupal platform the jQuery no longer works. It will however work when input through the Console.
jQuery:
carousel = (function(){
// Read necessary elements from the DOM once
var box = document.querySelector('.carouselbox');
var next = box.querySelector('.next');
var prev = box.querySelector('.prev');
// Define the global counter, the items and the
// current item
var counter = 0;
var items = box.querySelectorAll('.content-items li');
var amount = items.length;
var current = items[0];
box.classList.add('active');
// navigate through the carousel
function navigate(direction) {
// hide the old current list item
current.classList.remove('current');
// calculate th new position
counter = counter + direction;
// if the previous one was chosen
// and the counter is less than 0
// make the counter the last element,
// thus looping the carousel
if (direction === -1 &&
counter < 0) {
counter = amount - 1;
}
// if the next button was clicked and there
// is no items element, set the counter
// to 0
if (direction === 1 &&
!items[counter]) {
counter = 0;
}
// set new current element
// and add CSS class
current = items[counter];
current.classList.add('current');
}
// add event handlers to buttons
next.addEventListener('click', function(ev) {
navigate(1);
});
prev.addEventListener('click', function(ev) {
navigate(-1);
});
// show the first element
// (when direction is 0 counter doesn't change)
navigate(0);
})();
Removed it from inline to its own js file - sourced the file - works perfectly

Jquery Next and Prev Button Loop function

I have this simple next and previous function that i wrote but i am having one simple issue. On the last slider on click next, it shows a blank slider then on click next it starts all over as it is supposed to. What am i missing? Below is the jquery code;
$('div.contsliders').each(function(e) {
if (e != 0)
$(this).hide();
});
$('span.next').click(function(){
if ($('div.contsliders:visible').next().length != 0)
$('div.contsliders:visible').next().fadeIn(1000).prev().hide();
else {
$('div.contsliders:visible').hide();
$('div.contsliders:first').fadeIn(1000);
}
return false;
});
$('span.prev').click(function(){
if ($('div.contsliders:visible').prev().length != 0)
$('div.contsliders:visible').prev().fadeIn(1000).next().hide();
else {
$('div.contsliders:visible').hide();
$('div.contsliders:last').fadeIn(1000);
}
return false;
});
HERE IS THE JSFIDDLE LINK
I will really appreciate it mates, thanks.
That is because when it checks for the following condition for the div which you think it is the last using $('div.contsliders:visible').next().length gives .contsnextprev (hence length will still be 1 instead of 0 as assumed) so it shows that one instead of moving to the beginning, which happens when you click on it again. It is because .contsnextprev is the div next to the last slide #five.
if ($('div.contsliders:visible').next().length != 0)
$('div.contsliders:visible').next().fadeIn(1000).prev().hide();
You can change it to:
var $nxt = $('div.contsliders:visible').next('.contsliders');
if ($nxt.length != 0)
$nxt.fadeIn(1000).prev().hide();
Demo
Infact you can simplify this to just one handler as well:
$('div.contsliders:gt(0)').hide(); //Hide all but the first one
var $allSlides = $('div.contsliders'),
traverseDefault = "first", //set the defaults
actionDefault ="next";
$('span.next, span.prev').click(function(){
var traverse = traverseDefault,
action = actionDefault;
if($(this).is('.prev')){ //if action is prev
traverse = "last"; //set traverse to last in case nothing is available
action = "prev"; //set action to prev
}
var $curr = $allSlides.filter(':visible'), //get the visible slide
$nxtTarget = $curr[action](".contsliders"); //get the next target based on the action.
$curr.stop(true, true).fadeIn(1000).hide(); //hide current one
if (!$nxtTarget.length){ //if no next
$nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
}
$nxtTarget.stop(true, true).fadeIn(1000); //show the target
});
Demo

Categories