Reputation: 816
I am using a little bit of jQuery I wrote (I'm not too good with JavaScript/jQuery) that adds/removes a div (in this case, .show500, .hide500) on a browser resize. Here is the code:
//Completely add/remove divs completely from DOM on browser resize
$(function(){
$(window).resize(function(){
var win = $(this); //this = window
if (win.width() <= 500) {
$('.show500').add();
$('.hide500').remove();
} else if (win.width() > 500) {
$('.hide500').add();
$('.show500').remove();
}
});
});
So if the browser window is less than or equal to 500, add the .show500 into the DOM, and remove the .hide500 from the DOM.
Then, if the browser width is greator than 500, add the .hide500 into the DOM, and remove the .show500 from the DOM.
However, when I use this code, the .hide500 div shows up by default, and then when I shrink the browser size, the .hide500 div hides and the .show500 never shows up. Then when I expand the browser, both of the divs are gone.
Here is a jsFiddle of the code: http://jsfiddle.net/XzrPR/
I would appreciate any and all help from you guys!
Upvotes: 0
Views: 2255
Reputation: 44740
.remove() removes element from DOM, You can't get them back
Try this way
if (win.width() <= 500) {
$('.show500').show();
$('.hide500').hide();
} else if (win.width() > 500) {
$('.hide500').show();
$('.show500').hide();
}
Upvotes: 0
Reputation: 5699
A very simple Media Query example for hiding/showing, NOT adding/removing:
@media (mix-width:501px) and (max-width:9999px) {
.show500 { display:none; }
.hide500 { display:block; }
}
@media (max-width:500px){
.show500 { display:block; }
.hide500 { display:none; }
}
Upvotes: 0
Reputation: 92983
Your else if
can be reduced to just else
, and I think you meant to use .show()
instead of .add()
and .hide()
instead of .remove()
:
if (win.width() <= 500) {
$('.show500').show();
$('.hide500').hide();
} else {
$('.hide500').show();
$('.show500').hide();
}
However, you can also do this with pure CSS using media queries:
.show500 {
display: none;
}
.hide500 {
display: block;
}
@media all and (max-width: 500px) {
.show500 {
display: block;
}
.hide500 {
display: none;
}
}
http://css-tricks.com/css-media-queries/
Upvotes: 1
Reputation: 207537
Upvotes: 0