Celine305 Celine305 - 4 months ago 10
Javascript Question

onresize doesn't seem to work when in a loop (javascript)

I'm trying to call a function based on screen size inside a loop'.

The function works fine when the page is loaded, however, the content doesn't change when the window is resized.

Here's an example:
https://jsfiddle.net/celine305/BaNRq/27/

Any help would be much appreciated.

for (var i = 0; i < 2; i++) {
function red() {
$('#' + i + '').css('background', '#B60C0C')
.text('Screen Size RED');
}

function orange() {
$('#' + i + '').css('background', '#EBAE10')
.text('Screen Size ORANGE');
}

function green() {
$('#' + i + '').css('background', '#83ba2b')
.text('Screen Size GREEN');
}

var widths = [0, 500, 850];

function resizeFn() {
if (window.innerWidth >= widths[0] && window.innerWidth < widths[1]) {
red();
} else if (window.innerWidth >= widths[1] && window.innerWidth < widths[2]) {
orange();
} else {
green();
}
}
resizeFn();
window.onresize = resizeFn();
}

Answer
  1. Move your functions outside of the for loop
  2. Merge 3 functions to one
  3. Use a jQuery listener instead of JavaScript since you're using jQuery already

// You could also assign classes and use $(".className") instead of loop
function changeColor(color) {
    for(var i=0; i<2; i++){
        $('#'+i+'').css('background',color).text('Screen Size' + color);
    }
}

var widths = [0, 500, 850];

function resizeFn() {
    if (window.innerWidth>=widths[0] &&window.innerWidth<widths[1]) {
        changeColor('#B60C0C');
    } else if (window.innerWidth>=widths[1] && window.innerWidth<widths[2]) {
        changeColor('#EBAE10');
    } else {
        changeColor('#83ba2b');
    }
}

resizeFn();
$(window).resize(function() {
    console.log("resize");
    resizeFn();
})

JSFiddle renders the content inside a div so your code was never detecting the resize. I added a container to detect the resize, but otherwise you should use $(window).

Fiddle: https://jsfiddle.net/BaNRq/29/

Comments