S4nc7ion P
S4nc7ion P

Reputation: 47

Jquery function only loads after page refresh

I have roughly around 50 video thumbnails on a set page.

I would like to resize them depending on the resolution.

What I have tried was using @media query in css that did not work as expected then I moved over to this.

$(document).ready(function(event) {
  var width = $(window).width();
  // Change thumbnail size if browser width changes (should be in real-time)   
  if (width <= 1300) {
    console.log(width);
    $('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
  } else {
    $('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
  }
});

After inserting that script the video thumbnail size changes but as I adjust the browser the jQuery does not load and resize the thumbnail unless the page is refreshed ?

Im not sure as to why the jQuery is not loading the script in real time as the size (browser) changes.

Languages that I am using in this project : PHP, jQuery

Upvotes: 2

Views: 653

Answers (3)

Iftifar Taz
Iftifar Taz

Reputation: 839

you need to catch window resize event with jQuery and also write your code there.

$(window).resize(function() {
    var width = $(window).width();
    // Change thumbnail size if browser width changes (should be in real-time)   
    if (width <= 1300) {
        console.log(width);
        $('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
    } else {
        $('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
    }
});

To reduce code repetition you can make a function and call it in both $(window).resize() and $(document).ready()

Upvotes: 5

Cornel Raiu
Cornel Raiu

Reputation: 3005

You can do smth like this.

Note: this is untested code

function updateSizes(){
    var width = $(window).width();
    if (width <= 1300) {
        $('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
    } else {
        $('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
    }
}

$(document).ready(function(event) {
    updateSizes();
    // do other stuff here
});

$( window ).resize(function() {
    updateSizes();
    // do other stuff here
});

Upvotes: 0

Gregory Friedman
Gregory Friedman

Reputation: 76

function onResize() {
    var width = $(window).width();
    if (width <= 1300) {
        $('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
    } else {
        $('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
    }
}

$(document).ready(onResize);

$(window).resize(onResize);

This should work, but it would be much better if it were done with css. Would love you help you with that if you want to post what you tried. If you do it with css, you will not have the jumping on the page that'll occur when the js loads and changes those classes in and out.

Upvotes: 0

Related Questions