Search code examples
javascriptjquerycsswindowappend

Removing An Appended jQuery Div When Window Resizes - jQuery


I've appended some divs onto a nav with jQuery. These are set so they append if the window is bigger than 980px.

I would like these appended divs to be removed if the window is less than 980px. The jQuery I'm using in the example works, but only if the window is this size when loaded. When I re-size the window the appended divs don't get removed or added which is what I need.

I have a codepen here: http://codepen.io/emilychews/pen/jBGGBB

The code is:

jQuery

if ($(window).width() >= 980) {

$('.box').append('<div id="newbox">appended with jQuery</div>');

} 

if ($(window).width() <= 979) {

  $('#newbox').remove(); 

}

CSS

.box{
position: relative;
left: 50px;
top: 50px;
height: 30px;
width: 100px;
background: blue;
line-height: 30px;
text-align: center;
color: white;
}

#newbox {
margin-top: 20px;
width: 100px;
height: 100px;
background: red;}

HTML

<div class="box">Test</div>

Any help would be wonderful.

Emily


Solution

  • I've updated your codepen to show how you can accomplish this:

    Code Pen Here: http://codepen.io/anon/pen/ZeXrar

    // Logic inside of function
    function addRemoveDiv() {
      // Window Width pointer
      var wW = $(window).width();
      // If window width is greater than or equal to 980 and div not created.
      if (wW >= 980 && !$('#newbox').length) {
    
        $('.box').append('<div id="newbox">appended with jQuery</div>');
    
      // else if window is less than 980 and #newbox has been created.
      } else if (wW < 980 && $('#newbox').length) {
        $('#newbox').remove();
      }
    }
    
    // Initial function call.
    addRemoveDiv();
    
    // On resize, call the function again
    $(window).on('resize', function() {
      addRemoveDiv();
    })
    

    Also, I would recommend looking into debouncing the function call on resize so it's not called over and over and over again as the window resizes. Reference for that here:

    https://davidwalsh.name/javascript-debounce-function

    Also, libraries like Underscore and LoDash have debounce functions available when sourced:

    http://underscorejs.org/

    https://lodash.com/