Detecting browser width with media query using jQuery

I am trying to implement a precise way of figuring out the user's browser width based on a media query. For example, I have an element div called #check_screen initially it'll be displayed as a block element. If the browser width is < 420px, then #check_screen will have a display: none property. This is what I have tried so far:

HTML

<div id='check_screen'></div>

CSS

#check_screen{
    display: block;
}

@media only screen and (max-width: 420px){
    #check_screen{
        display: none;
    }
}

jQuery

$(document).ready(function() {
    // run test on initial page load
    checkSize();

    // run test on resize of the window
    $(window).resize(checkSize);
});

//Function to the css rule
function checkSize(){
    if ($("#check_screen").css("display") == "none" ){
        console.log("hello");
    }
}

For some reason, it is not working correctly. When I resize the screen to < 420px, the message is not displayed to the console. I have also tried using the :visible jQuery selector, but that does not work either. I am using Chrome as my browser.

Answers 1

  • I think you have a syntax error: $(window).resize(checkSize); should be

    $(window).resize(function(){
        checkSize();
    });
    

    That correction worked for me with no other changes.


Related Articles