Bill Bronson
Bill Bronson

Reputation: 560

Fire appendTo() only once when document is ready (jQuery)

I want to remove the dynamically created "onsale" button when the page loads and put it a bit more up in the DOM.

But since there are 3 Elements that has this class he is firing it 3 times for each element and adds 3 "onsale" buttons to each position.

I tried to bind it to the one() handler of jQuery and switched between some events like click, load, ready, etc. Nothing was changing at all.

Also tried to a counter or just count the elements via length() but same as before.

Heres my code:

$('.onsale').one('click', function () { 

    $('.onsale').appendTo('.woocommerce-loop-product__title');
    console.log('fired!');
});

Element that should move:

<span class="onsale">Angebot!</span>

See live test environment here(scroll down to the bottom): Link

Upvotes: 0

Views: 389

Answers (1)

Yasir
Yasir

Reputation: 687

You need to bind only the first element using the selector:

$( document ).ready(function() { 
   $('.onsale:first').appendTo('.woocommerce-loop-product__title');
});

Upvotes: 2

Related Questions