How can I make this JQuery code more responsive?

68 Views Asked by At

I am trying to create a progress bar that adjusts based on device's width but I am having an issue.

With this specific setup, every time the device width changes, the progress bar's width doesn't, so it's not really usable if somebody switches to landscape, it breaks the site.

Just a quick note, I have 2 progress bars, one stacked on top of each other.

EDIT: Here is a working solution, check below

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_block-1545-2104" class="ct-div-block progress-bar"></div>
<div id="div_block-1545-2104" class="ct-div-block progress-bar2"></div>
$carousel.on("scroll.flickity", function (event, progress) {
    const $progressBar = $(".progress-bar");
    const divWidth = $(".progress-bar2").width();

    progress = Math.max(0, Math.min(1, progress));
    $progressBar.width(progress * divWidth);
});
1

There are 1 best solutions below

7
On

Changes of width due to device properties - like landscape/portrait - should best be handled via CSS, but you need to hook into window-resize-event. You will probably want to look into some throttle/debounce too though, since these sort of events (resize,scroll,etc.) may fire repeatedly in short order!

$(window).on('resize', function(e){ $progressBar.width( Math.max(0,Math.min(1,progress))*divWidth); } )

For clarity:

var $progressBar = $('.progress-bar'),
    divWidth = $('.progress-bar2').width();

$carousel.on('scroll.flickity', function(event, progress){
    console.debug( "the scroll.flickity event fired." );
} );
$(window).on('resize', function(e){ 
    console.debug( "the window:resize event fired. [throttle!!?!]" );
    progress = Math.max( 0, Math.min(1, progress));
    $progressBar.width(progress * divWidth);
} )