Lumoris
Lumoris

Reputation: 29

I want to hide a div by resizing the window

I tried to hide a div with jQuery with the following code:

$(window).resize(function(){
  if ( window.innerHeight < 750 ) {
    $("footer").animate({'height' : '0px'}, 500);
  }
  if ( window.innerHeight > 750 ) {
    $("footer").animate({'height' : '35px'}, 500);
  } 
});

I have tested it in Chrome and it only works once. It only disappears and never appears again by resizing.

Is there a mistake in my code or is it the wrong solution?

Thank you in anticipation!

Upvotes: 0

Views: 3370

Answers (3)

Learner
Learner

Reputation: 4004

Here is jQuery Implementation:

Suppose you want to hide div1 when the window width is less than 750px and display it again if the window width is greater than 750px

HTML

<div id="div1">
</div>

CSS

#div1{
    width:100%;
    padding:30px;
    background:#1d1d1d;
}

jQuery

$(window).resize(setDivVisibility);
function setDivVisibility(){
     if (($(window).width()) < '750'){  
     $('#div1').css('display','none');  
     } else {  
     $('#div1').css('display','block');  
     } 
 }

Working jsfiddle: http://jsfiddle.net/a8V9V/

Upvotes: 0

Manoj Yadav
Manoj Yadav

Reputation: 6612

That means this condition if ( window.innerHeight > 750 ) { is never executing because browser window.innerHeight is less than 750. To see the value in console log it like this:

console.log(window.innerHeight);

Upvotes: 0

Derek Story
Derek Story

Reputation: 9583

Easy way is to use a media query: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

For example, if you have an id of #divOne, you style the div as normal and add a separate media query as display: none; for when the window shrinks to a specified width. In this case, the div hides when the width of the window is below 600px:

#divOne {display: block; height: 200px; background: #000; }

@media (max-width: 600px) {
  #divOne {
    display: none;
  }
}

Upvotes: 1

Related Questions