I have this code:
var res = [1024, 1280, 1600],
vals = [1, 2, 3];
I want to assign a value to a variable on window.resize depending on the resolution that matches in the res array. So i came up with this:
function update() {
res.forEach(function( res, i ) {
someVariable = $(window).width() < res ? vals[ i ] : 4;
});
}
$(window).resize( update );
The problem is that it only works for 1600 but not for all the other resolutions. But if I do the following (hard-coded) it works just fine:
function update() {
someVariable = $(window).width() < 1024 ? 1
: $(window).width() < 1280 ? 2
: $(window).width() < 1600 ? 3
: 4;
}
Any ideas on how to make this work dynamically?
Edit: I’m thinking I have to break the loop at some point but can’t figure out the condition to test…
You need to
breakthe loop when first time the condition becomes true and value is assigned tosomeVariableas with width less then 1024 is also less then 1280 and 1600 and finally you will get the last one which is 1600.Edit as per AlexStack comments, to break the forEach loop as dicussed in this post you can use the following technique.