0

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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh I see! My resize function was outside the document.ready function. Thank you!
You could also just use if ($(window).width() < 420) {console.log("Hello")}; inside the $(window).resize( function() { so JS is handling the screen size check instead of relying on CSS media-queries.
0

Assign unvisible div and set its color to black.

If resized, change its color to green.

Javascript would be like

var check = $("element").css("background-color");

if(check == "black" {
}

else if...

1 Comment

Have you included jquery, and then this script? Did you put this in onLoad? Post your code on the fiddle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.