Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  10] [ 6]  / answers: 1 / hits: 23088  / 11 Years ago, mon, october 14, 2013, 12:00:00

I need to execute a specific function based on screen size and screen size changes (Responsive)



So lets say I have 3 functions (For Example)



function red() {
$('div').css('background','#B60C0C')
.text('Screen Size RED');
console.log('RED');
}

function orange() {
$('div').css('background','#EBAE10')
.text('Screen Size ORANGE');
console.log('ORANGE');
}

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


I need to execute function green() when the screen width size 500px or lower



And function orange() when the screen width size 501px to 850px



And function red() when the screen width size 851px or higher



enter



I tried to use resize() but the problem is executing the function when resizing the browser for each pixel repeat executing the same function and this is a very bad way to perform



I need to execute the function when break the point of the screen width size



Ready to use code on jsfiddle http://jsfiddle.net/BaNRq/


More From » jquery

 Answers
49

Meh; here's a solution.



You could cache the lastBoundry determined to invoke the functions only when a change occurs.



// define the boundries
var bounds = [
{min:0,max:500,func:red},
{min:501,max:850,func:orange},
{min:851,func:green}
];

// define a resize function. use a closure for the lastBoundry determined.
var resizeFn = function(){
var lastBoundry; // cache the last boundry used
return function(){
var width = window.innerWidth; // get the window's inner width
var boundry, min, max;
for(var i=0; i<bounds.length; i++){
boundry = bounds[i];
min = boundry.min || Number.MIN_VALUE;
max = boundry.max || Number.MAX_VALUE;
if(width > min && width < max
&& lastBoundry !== boundry){
lastBoundry = boundry;
return boundry.func.call(boundry);
}
}
}
};
$(window).resize(resizeFn()); // bind the resize event handler
$(document).ready(function(){
$(window).trigger('resize'); // on load, init the lastBoundry
});


Fiddle: http://jsfiddle.net/BaNRq/3/


[#74992] Sunday, October 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brodyfrancisi

Total Points: 1
Total Questions: 102
Total Answers: 89

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
brodyfrancisi questions
;