Skip to content Skip to sidebar Skip to footer

Jquery Not Firing On First Click

I'm making a custom jQuery slider and for whatever reason, my jQuery function is not firing on the first click, only subsequent clicks. I've searched stackoverflow for solutions,

Solution 1:

I made a few changes to the javascript, I think the first click issue was that on the animate section, it was animating before calculating the new margin. I also updated some values to theWidth variable for consistency.

Also the if statement on the .prev click was stopping the slider getting back as widthCount doesn't get above totalWidth.

https://jsfiddle.net/xyvzdenj/

var theTestimonial = jQuery('.testimonial-wrapper');
var theWidth = theTestimonial.width();
var widthCount = theWidth;

jQuery('.testimonial-container').wrap('<div class="extra-wrapper"></div>');
jQuery('.testimonial-container').css('margin-left', '0px');

jQuery('.extra-wrapper').css({
    width: function () {
        return theWidth;
    },
    position: 'relative',
    overflow: 'hidden'
});

//get total of image sizes and set as width for ul var totalWidth = theTestimonial.length * theWidth;
jQuery('.testimonial-container').css({
    width: function () {
        return totalWidth;
    }
});


jQuery('.next').on("click", function () {
    if (widthCount < totalWidth) {
        widthCount = widthCount + theWidth;

        jQuery('.testimonial-container').animate({
            "margin-left": "-=" + theWidth
        }, 750);
    }


});

jQuery('.prev').on("click", function () {
    if (widthCount > theWidth) {
        jQuery('.testimonial-container').animate({
            "margin-left": "+=" + theWidth
        }, 750);
        widthCount = widthCount - theWidth;
    }


});

Solution 2:

FYI I had just the same problem, an event fired on second click. The cause turned out to be simple, I accidentally swapped actions:

$('.element').click(function{
  $(this).toggleClass('iWantAction');
  if($(this).hasClass('iWantAction')){
    sitStill(); //WRONG! Had to be doAction1();
  } else {
    doAction(); //WRONG! Had to be sitStill();
  }
})

So, the outcome was the same, the event didn't fire until class was added on first click and then removed on second

Post a Comment for "Jquery Not Firing On First Click"