Tim
Tim

Reputation: 137

Hide() and show() on window resize in JavaScript

I am trying to use .hide() to hide the anchor element when it is less than 500px width and .show() again when the window size is greater than 500px width.

So it changes depending on the window size.

application.js

$(document).ready(function() {

 var windowWidth = $(window).width();

 function checkWidth() {
    if (windowWidth < 500) {
        $("#down-arrow a").hide()
    }
    if (windowWidth > 500){
        $("#down-arrow a").show()
    }
 }
 checkWidth() ;

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

index.html

<div id="down-arrow">
   <a href="#"></a>
</div>

Upvotes: 2

Views: 5283

Answers (3)

Shibu Thomas
Shibu Thomas

Reputation: 3196

Using Jquery.Get current width using $(window).width()

$(window).resize(setDivVisibility);
function setDivVisibility(){
     if (($(window).width()) < '500'){  
     $('#down-arrow a').css('display','none');  
     } else {  
     $('#down-arrow a').css('display','block');  
     } 
 }

Using CSS

@media only screen and (max-device-width: 500px) {
    #down-arrow a{display:none;}
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 707318

You have to get the current width inside checkWidth() function so that it's the latest value:

$(document).ready(function() {

 function checkWidth() {
    var windowWidth = $(window).width();
    if (windowWidth <= 500) {
        $("#down-arrow a").hide();
    } else {
        $("#down-arrow a").show();
    }
 }
 checkWidth();

 $(window).resize(checkWidth);
});

Probably should also change one of the comparisons to include the 500 value so you do something when the width is exactly 500. And, I switched the code to use an if/else rather than two if statements.

You could also just use .toggle() and pass it a boolean:

$(document).ready(function() {

 function checkWidth() {
    $("#down-arrow a").toggle($(window).width() > 500);
 }
 checkWidth();

 $(window).resize(checkWidth);
});

And, you could implement all of this with CSS media query rules too and not have to use Javascript.

Upvotes: 4

wmehanna
wmehanna

Reputation: 394

Using Javascript to show/hide a DOM element is not reccommended since the best way to acheive this is to use css @Mediaquery properties.

Here's an example :

@media screen and (max-width: 500px) {
    #down-arrow a{
        display : none;
    }
}

Upvotes: 4

Related Questions