Home > Net >  Use variable value from window resize function in another function
Use variable value from window resize function in another function

Time:10-07

I have a carousel that I'm trying to get the currently visible number of slides to announce on "next" button click.

I'm able to see that on resize, I have the correct number of slides being logged, but can't seem to pass the visibleSlides value to the getSlideCount function properly.

The screen reader is reading "Next undefined items", instead of "Next {number} items"

How can I properly pass the value from the resize function to my next item click function?

$(window).resize(function () {
   let visibleSlides = $(".carousel-item.slick-active").length;
   getSlideCount(visibleSlides)
});
            
function getSlideCount(visibleSlides){
   return visibleSlides;
}
getSlideCount();
$(".slick-next").click(function(){
    $("#counter").append(`Next ${getSlideCount()} items`);
});

CodePudding user response:

You call getSlideCount() without argument. Change to this.

let visibleSlides;
$(window).resize(function () {
    visibleSlides = $(".carousel-item.slick-active").length;
});

$(document).ready(function() { 
    visibleSlides = $(".carousel-item.slick-active").length;
});

$(".slick-next").click(function(){
    $("#counter").append(`Next ${visibleSlides} items`);
});
  • Related