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


i'm trying call function based on screen size inside loop'.

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

here's example: https://jsfiddle.net/celine305/banrq/27/

any appreciated.

for (var = 0; < 2; i++) {   function red() {     $('#' + + '').css('background', '#b60c0c')       .text('screen size red');   }    function orange() {     $('#' + + '').css('background', '#ebae10')       .text('screen size orange');   }    function green() {     $('#' + + '').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(); } 

  1. move functions outside of for loop
  2. merge 3 functions one
  3. use jquery listener instead of javascript since you're using jquery already

// assign classes , 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 content inside div code never detecting resize. added container detect resize, otherwise should use $(window).

fiddle: https://jsfiddle.net/banrq/29/


Comments