Change attribute from a div when window size change

2k Views Asked by At

I work with jQuery mobile. In this case i want to add the data-role collapsible to a div, when the screen width less than 960px is.

In my example it only works when you load the site. But I want, that it also works when I resize the browser without reload the page.

The change from > 960 px to < 960 px is for example when you rotate a tablet or resize the browser window by hand.

$( document ).on( "pagebeforecreate", function() {
    if ($(window).width() < 960) {
       $(".medis_collaps").attr("data-role","collapsible")
    }
});

Edit

.resize() doesn't work , because it seems that I have to reload the page to make data-role="collapsible" working.

3

There are 3 best solutions below

1
On

use also resize

$( window ).resize(function() {
   if ($(window).width() < 960) {
       $(".medis_collaps").attr("data-role","collapsible")
    }
});
1
On

You can bind resize and load events as following:

$(window).on('resize load pagebeforecreate', function(){
    if ($(window).width() < 960) {
       $(".medis_collaps").attr("data-role","collapsible")
    }
});

In this case there is no necessity to bind same functionality for ever event.

1
On

You can use like this:

$( document ).on( "load resize pagebeforecreate", function() {
    if ($(window).width() < 960) {
       $(".medis_collaps").attr("data-role","collapsible")
    }
});