Nicat
Nicat

Reputation: 39

remove function doesn't remove as expected

var offset = 0;
var delay = 100;    
$(document).ready(function(){

    for(let z=0;z<=6;z++){
        setDelay(z);
        delay += 100;
    }

    function setDelay(z) {
        setTimeout(function(){

            //Create clone
            var c2 = $(".cHeader").eq(0).clone().appendTo("#contact");

            //Set position
            offset += 20;
            $(c2).css("left", offset+"px");

        }, delay);

    }

    $(".cHeader").first().remove();

});

I am trying to create a clone of an element every 100ms until it reaches 7, and remove the very first one after creating 7 clones. The code above can create 7 clones without any problems, but when I add $(".cHeader").first().remove(); to remove the first element, it removes every element with cHeader class. But I only want it to remove the first element with cHeader class.

Html:

<div id="contact">
    <h1 class="cHeader">hdr</h1>
</div>

Upvotes: 0

Views: 50

Answers (2)

Shiny
Shiny

Reputation: 5055

If you use setInterval rather than setTimeout you can avoid globals, and also have the code more readable ( I believe ).

Also, move the $('.cHeader').first().remove() to be called after the 7 loops, so that the element remains for you to clone from - before you were removing it just before the start of the first loop

$(document).ready(function() {

  function cloneElements() {
    let i = 0;
    let cloneInterval = setInterval(() => {
      // Create clone
      let count = $('#contact .cHeader').length;
      let c2 = $(".cHeader").first().clone().appendTo("#contact");

      // Set position
      c2.css('left', `${count * 20}px`);

      // Stop after 7
      i = i + 1;
      if (i >= 7) {
        clearInterval(cloneInterval);
        $('.cHeader').first().remove();
      }
    }, 100);
  }

  cloneElements();

});
.cHeader {
  position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="contact">
  <h1 class="cHeader">hdr</h1>
</div>

Upvotes: 1

fdomn-m
fdomn-m

Reputation: 28611

it removes every element with cHeader class.

it's actually removing the header before you can clone so there's nothing to clone.

This code:

 setTimeout(cloneHeader, 100)
 removeHeader()

is the same as:

 removeHeader()
 cloneHeader()

ie the removeHeader() is called before the cloneHeader code so there's nothing to clone.

You can instead hide the header, eg:

$(".cHeader").first().hide()

then when you clone:

var c2 = $(".cHeader").eq(0).clone().appendTo("#contact");
c2.show();

Upvotes: 1

Related Questions