Lieutenant Dan
Lieutenant Dan

Reputation: 8274

Show and hide div with Window Size JavaScript?

I'm trying to show a div based on two or preferably three defined window sizes for mobile.

I'm currently trying to implement:

<script>

if( $(window).width() > 768 ) {
    $('#div1').show();
    $('$div2').hide();
} else {

}

if( $(window).width() < 768 ) {
    $('#div1').hide();
    $('$div2').show();
} else {

}

</script>

But it isn't working what am I doing wrong here?

Upvotes: 0

Views: 2707

Answers (2)

basarat
basarat

Reputation: 275917

You need to do it inside the window.resize http://api.jquery.com/resize/ event

<script>
$(window).resize(function{
if( $(window).width() > 768 ) {
    $('#div1').show();
    $('#div2').hide();
} else {

}

if( $(window).width() < 768 ) {
    $('#div1').hide();
    $('#div2').show();
} else {

}
});
</script>

And yes the div2 should have # not $

Upvotes: 3

dsdev
dsdev

Reputation: 1124

Your div2 selector is wrong. It should be a # not a $.

Also, you should consider using media queries for this!

#div2 {
  display: none;
}

@media screen and (max-width : 768px) {
  #div1 {
    display: none;
  }
  #div2 {
    display: block;
  }
}

Upvotes: 4

Related Questions