简体   繁体   中英

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

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/

You should use event listeners.

$(document).ready(function() {
    function checkMyDiv(calledByResize) {
        if($(window).width() >= 980 && $('#newbox').length < 1) { // "$('#newbox').length < 1" will prevent to add lots of div#newbox elements
            $('.box').append('<div id="newbox">appended with jQuery</div>');
        } else if (calledByResize === true && $('#newbox').length > 0) {
            $('#newbox').remove();
        }
    }
    $(window).resize(function() {
        checkMyDiv(true);
    });
    checkMyDiv(false);
});

You may also want to use css rules, like display:none|block; instead of removing or appending div#newbox element everytime the window resizes.

I think you need to add an event listener on the window object, listening for the .resize() event:

https://api.jquery.com/resize/

Then in the callback function you should be able to check whether the new size is below your threshold, so you can remove the div in that case.

$(window).resize(function () {
  // Check window width here, and remove div if necessary
})

You're almost there, you just need the resize event, and for it to be applied after the ready event:

(function($) {
    $(function() {
        $(window).on('resize', function() {
            if ($(window).width() >= 980) {
                $('.box').append('<div id="newbox">appended with jQuery</div>');
            } 

            if ($(window).width() <= 979) {
                $('#newbox').remove(); 
            }
        }).trigger('resize');
    });
})(jQuery);

Although, it should be noted this will actually append an additional copy of your newbox on every single resize event, which I'll assume you don't want. So, we'll sort out that problem.

We can also do a few simple optimisations here to make the code slightly more efficient, such as storing our element selectors and window width in variables:

(function($) {
    $(function() {
        var $window = $(window),
            newBox = $('<div id="newbox">appended with jQuery</div>'),
            box = $('.box');

        $window.on('resize', function() {
            var windowWidth = $window.width();

            if (windowWidth >= 980) {
                if(!$.contains(document, newBox[0])) {
                    box.append(newBox);
                }
            } else if (windowWidth <= 979) {
                if($.contains(document, newBox[0])) {
                    newBox.remove();
                }
            }
        }).trigger('resize');
    });
})(jQuery);

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