insertAfter inserting code twice

1.6k views Asked by At

I'm trying to insert a few lines of new code into my site. The code needs to be inserted when the browser width is less than 768px, and if the code already exists, it doesn't need to be inserted again. For some reason whenever I resize the browser to less than 768, the code is inserted twice and then once more every time I resize it. Does anyone know why this line of code is being inserted more than once?

$(window).resize(function() {
  if ($(window).width() < 768) {
    if ($(document).not('#step-4-circle')) {
      $('<div id="step-4-circle" class="step-circle"><div class="inner"><span class="number">4</span><span class="title">FULFILL ORDERS</span><span class="subtitle">where you want</span></div></div>').insertBefore('#how-step-3');
    }
  }

});
2

There are 2 answers

0
Kevin Bowersox On BEST ANSWER

Adjust the conditional to check if any elements were selected:

if ( $('#step-4-circle').length == 0 ) {
    $('<div id="step-4-circle" class="step-circle"><div class="inner"><span class="number">4</span><span class="title">FULFILL ORDERS</span><span class="subtitle">where you want</span></div></div>').insertBefore('#how-step-3');
}

JS Fiddle: http://jsfiddle.net/3zP8H/1/

0
Ram On

.not() method removes the matching elements from the collection, $(document) returns a collection which has only one element(the document object), you are trying to exclude an element with ID of step-4-circle which doesn't exist in the set. Also as an object is a truthy value your condition is always true, you should use length property as @Kevin mentions.

Also note that resize event is fired many times, if you want to listen to this event it would be better to use .setTimeout() function:

var t = null; 
var $w = $(window).resize(function() {
     clearTimeout(t); 
     t = setTimeout(function(){
         if ( $w.width() < 768 ) {
              if ($('#step-4-circle').length == 0)
              $('<div id="step-4-circle">...</div>').insertBefore('#how-step-3');
         } else {
              $('#step-4-circle').remove();
         }
     }, 80);
});