Lately I’ve been working with a lot of responsive web designs, and this type of work is obviously related to CSS, but like any front-end work, javascript (in this case jQuery) is always in the mix. I wouldn’t call it challenging, but I had to come up with a solution to inform jQuery of what screen width breakpoint the responsive design was displaying.
Since we have the ability to change the styling of an element at each breakpoint in our designs, we can simply apply a different value for a specific CSS rule at each breakpoint. In the case of the latest design I’ve been working on, I chose to change the text color of some text that that was being hidden by an image replacement.
A Sample Stylesheet
/* Breakpoint identifier rgb(0,0,0) */ #bp{color:#000;} /* >= 300 PX */ @media only screen and ( min-width:300px ){ /* Breakpoint identifier rgb(1,1,1) */ #bp{color:#010101;} } /* >= 480 PX */ @media only screen and ( min-width:480px ){ /* Breakpoint identifier rgb(2,2,2) */ #bp{color:#020202;} } /* >= 600 PX */ @media only screen and ( min-width:600px ){ /* Breakpoint identifier rgb(3,3,3) */ #bp{color:#030303;} } /* Don't forget about old IE */ /* Breakpoint identifier rgb(9,9,9) */ .lt-ie9 #bp{color:#090909;}
The jQuery
(function($){ // Local Namespaced Functions var namespace = { /* Get the media query breakpoint number */ get_breakpoint: function(){ var color = $('#bp').css('color'); var limit = 9; for( var i = 0; i <= limit; i++ ){ var rgb = 'rgb(' + i + ', ' + i + ', ' + i + ')'; if( color == rgb ){ return i; } } return limit; } }; window.funcs = namespace; })(this.jQuery); // Document Ready Function $(document).ready(function(){ /* Set breakpoint indicator */ var bp = funcs.get_breakpoint(); /* Window resize */ $(window).resize(function(){ var new_bp = funcs.get_breakpoint(); /* Do something with new_bp */ console.log( new_bp ); }); /* Do something with bp */ console.log( bp ); });
Usage
So you can see that there’s not much to this. Use the bp variable in your jQuery when you need to identify the initial breakpoint, or use the new_bp variable when the screen width has changed.