简体   繁体   中英

jQuery add/remove from DOM on browser resize

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!

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/

  • You want to use .show() not .add()
  • You want to use .hide() and not .remove()

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; }
}

.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();
 }

working fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM