ovokuro ovokuro - 2 months ago 9
Javascript Question

How can I call a function depending on screen width?

I have 2 functions, and I want them to be called depending on the screen width.

This is what I have tried:

var winWidth = $(window).width();

var sections = function() {
$('.image').each(function(){
var $this = $(this),
x = $this.find('img').width()
$this.width(x);
});
};

var sectionsMobile = function() {
$('.image').find('img').css({
'height': 'auto',
'width': '100%'
});
};

function checkSize() {
if (winWidth >= 800) {
sections();
} else {
sectionsMobile();
}
}
jQuery(window).on('load resize', checkSize);


When the page loads, it works and the CSS is applied. However resizing between the 800px boundary doesn't switch between the functions.

Full demo here: http://codepen.io/sol_b/pen/PzgdWy

Any help much appreciated.

Answer

Try this:

$(window).on("load resize",function(){

    if($(this).width() >= 800 )
        sections();

    else
        sectionsMobile();

});