Home > Software design >  Trigger click function in another variable function after Ajax
Trigger click function in another variable function after Ajax

Time:03-30

My code works fine on window load, I have placed it in a function to reset content width after ajax. My problem is that the anchor to enable the contents to slide stops working after Ajax. Any ideas what I am doing wrong?

Here is my code:

     function slideMyContent(){
         $(document).find('.selector').each( function(){
            var $slider = $(this),
            $sliderContainer = $slider.find(".slider-container"),
            $sliderList = $slider.find('.slider-list'),
            $sliderItem = $slider.find('.slider-item'),
            $sliderItemInner = $slider.find('.slider-item-inner'),
            $sliderItemInnerEmpty = $slider.find('.slider-item-inner:empty'),
            $sliderButton = $slider.find('.slider-button'),
            $prevButton = $(document).find('.slider__button--prev'),
            $nextButton = $(document).find('.slider__button--next'),
            setItemWidth = function(){
                // some codes to set content width which works fine even after Ajax
            },
            slide = function(){
                var $button = $(this),
                    dir = $button.data('dir'),
                    curPos = parseInt($sliderList.css('left')) || 0,
                    moveto = 0,
                    containerWidth = $sliderItemInner.length ? $sliderContainer.innerWidth()   1 : $sliderContainer.innerWidth(),
                    listWidth = $sliderList.innerWidth(),
                    before = (curPos   containerWidth),
                    after = listWidth   (curPos - containerWidth);
                if(dir=='next'){
                    moveto = (after < containerWidth) ? curPos - after : curPos - containerWidth;
                    $prevButton.toggle(moveto != 0);
                    $nextButton.toggle(after > containerWidth);
                } else {
                    moveto = (before >= 0) ? 0 : curPos   containerWidth;
                    $prevButton.toggle(moveto != 0);
                    $nextButton.show();
                }
                    $sliderList.animate({left: moveto});
            };
            $(window).resize(function(){
                setItemWidth();
                slide();
            });
            setItemWidth();
            $sliderButton.on('click', slide); // This is where I have a problem (Not woking after Ajax)
        });
    }

CodePudding user response:

Thanks to everyone. I ended up removing the slide function from the main function and doing my anchor click from a stand-alone on click function like:

   $(document).on('click', '.slider-button', function(){
      slide();
   });

If anyone has any better way to do what I intend to do without the additional lines of code, please feel free to share. I'm hoping it will help someone someday. Cheers!

  • Related