Dylan Hsiao
Dylan Hsiao

Reputation: 131

On the fly / dynamic variable - responsive web

I just finished writing some logic and it works. But I realize I need to have dynamic variables in which their values would change when resizing the browser. See the following code example:

(function(){

  var carouselCellUnitHeight = $('.carousel .carousel__cell').height(),
  carouselCellCounts = $('.carousel .carousel__cell').length,
  moveDis = -(carouselCellUnitHeight * ((carouselCellCounts/2)-1)),

  $('.carousel__content-wrapper').css({
    'transform' : 'translateY('+ moveDis +'px)'
  });

})(); 

One of the possible way I could think of is to substitute "moveDis" with all the variable calculations, but I don't think it is a good idea to mess with the concatenation inside .css() jQuery method.

In short, what is the best way to do this on the fly? Thanks!

Upvotes: 0

Views: 35

Answers (1)

Jason McFarlane
Jason McFarlane

Reputation: 2175

If your logic is correct you can put it into its own function instead of an IFFE and call it on load and resize to do the calculations every time you resize the browser

function carousel() {
  var carouselCellUnitHeight = $('.carousel .carousel__cell').height(),
  carouselCellCounts = $('.carousel .carousel__cell').length,
  moveDis = -(carouselCellUnitHeight * ((carouselCellCounts/2)-1)),

  $('.carousel__content-wrapper').css({
    'transform' : 'translateY('+ moveDis +'px)'
  });

}

$(document).ready(carousel); 
$(window).resize(carousel);

Upvotes: 1

Related Questions