Dynamically add class to browser size (viewport width)
I have an element called jobfilter that I want to add to the class depending on the width of the viewport i.e. when i resize my browser to <1000px i want to add .hidden class to .jobfilter.
I have now managed to get half the work done with this link: $ (window) .width () does not match media query . Using this:
function checkPosition() {
if (window.matchMedia('(max-width: 767px)').matches) {
//...
} else {
//...
}
}
Here's my JSFiddle: http://jsfiddle.net/ck55Lf01/10/ .
If you resize the browser and refresh the page, the job filter is hidden, but I would like it to happen dynamically and not on page refresh, thanks for your help!
source to share
This is the function I use to dynamically check the width of the window when resizing, I wrapped it in a document ready function that passes the $ parameter as a parameter to prevent any conflicts that might arise with other javascript libraries that use $. For example, if you were to use your function inside a wordpress theme or plugin.
Jsfiddle example: http://jsfiddle.net/larryjoelane/ck55Lf01/24/
JavaScript:
/*
document ready function used to prevent conflict with other javascript libraries
that use the $ parameter
*/
jQuery(document).ready(function($){
//get the window width
var winWidth = $(window).width();
//set the maxWidth
var maxWidth = 1000;
//if the window width is less than the maxWidth pixels on document loading
if(winWidth < maxWidth){//begin if then
//add the class hidden to .jobFilter
$(".jobfilter").addClass("hidden");
}//end if then
$(window).resize(function(){//begin resize event
//get the window width
var winWidth = $(window).width();
//set the maxWidth
var maxWidth = 1000;
//if the window width is less than maxWidth pixels
if(winWidth < maxWidth){//begin if then
//add the class hidden to .jobFilter
$(".jobfilter").addClass("hidden");
}
else{
//remove the class hidden
$(".jobfilter").removeClass("hidden");
}//end if then else
});//end window resize event
});//end document ready function
source to share
Little known fact: matchMedia
Has an event listener:
function handleMedia(mql) {
if (mql.matches) {
// media query matches
} else {
// media query does not match
}
}
var mql = window.matchMedia('(max-width: 767px)').addListener(handleMedia);
handleMedia(mql);
The event listener will run every time the browser matches or cancels a media request. In your case, I would recommend manually triggering the handler (as shown in the example) to get the correct set of classes when loaded.
This example is taken from MDN (although it's pretty well hidden).
source to share
$(document).ready(function(){
DOaction(); // run function after document ready
$(window).on('resize',DOaction); // on resize window run function
});
// function to add and remove hidden class
function DOaction(){
if($(window).width() <= 1000){
$(".jobfilter").addClass('hidden');
}else{
$(".jobfilter").removeClass('hidden');
}
}
source to share