eve_mf
eve_mf

Reputation: 825

Appending multiple items on click

I have this jquery function:

html:

<div class="item">
    <div class="imageWrap">
        <img class="img-responsive" src="images/wine_large.png" alt=""/>
    </div>
</div>

js:

function reserve_selected() {
    $('.myReserve').on('click', ".item", function(e) {
        e.preventDefault();
        $(this).toggleClass('selected');
        if($(this).hasClass('selected')) {
            $(this).find('img').css("display", "none");
            $(this).find('.imageWrap').append('<span class="icon-selected-tick"></span>'); 
        } else {
           $(this).find('.imageWrap').remove('<span class="icon-selected-tick"></span>');
           $(this).find('img').css("display", "block");
        }
    });
}

The thing is.... when I click on the ".item", I want to add the class .selected. If the item is selected, the image needs to hide and instead place an icon. I can't modify the html, so I am adding the icon with append.

If I click again, and the item has already class selected, the product image needs to appear again, and the icon disappear, but if I click, it adds it properly, if I click again, it removes it and shows back the image, but If I click again, the icon appears twice, then I click again, the image appears fine and the icons disappear, but if I click again, the icon appears three times and so on, what am I doing wrong? Why is it appending it twice?

Thank you

Upvotes: 0

Views: 51

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

You can't provide the HTML as a property to be removed, you need to select the element itself. There's also a several optimisations you can make to the code. Try this:

function reserve_selected() {
  $('.myReserve').on('click', ".item", function(e) {
    e.preventDefault();
    var $el = $(this).toggleClass('selected');

    if ($el.hasClass('selected')) {
      $el.find('img').hide()
      $el.find('.imageWrap').append('<span class="icon-selected-tick">Tick</span>');
    } else {
      $el.find('.imageWrap span').remove();
      $el.find('img').show()
    }
  });
}

reserve_selected();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myReserve">
  <div class="item">
    <div class="imageWrap">
      <img class="img-responsive" src="images/wine_large.png" alt="" />
    </div>
  </div>
</div>

Upvotes: 1

Related Questions