skip to Main Content

I have a portfolio where I list portfolio items.
I have classes so when you click the item, it has an effect.
For some reason, when I click the minus button, it doesn’t remove the class ‘on’.

Here is the jQuery:

  $('.portfolio-item').click(function() {
    $(this).addClass('on');
  });
  $('.minus').click(function() {
    $(this).closest('.portfolio-item').removeClass('on');
  });

and here is the element set up:

<div class="portfolio-item" style="margin-top: 5px; ">
   <div class="overlay">
      <h1>LOW POLY ISLANDS</h1>
      <h3>LOW POLY</h3>
   </div>
   <div class="about">
      <h1>LOW POLY ISLANDS</h1>
      <h3>LOW POLY</h3>

      <div class="descrip">
         This is a low poly island make in Blender and edited in Photoshop.
      </div>

      <div class="minus"></div>
      <div class="plus"></div>
    </div>
    <img src="https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/57909c29180525.55fc4b1875c26.png" width="100%" />
</div>

How do I fix this – I want to be able to remove the class ‘on’ when I click on ‘minus’.

2

Answers


  1. you need to use e.stopPropagation()

    $('.minus').click(function(e) {
          e.stopPropagation();
        $(this).closest('.portfolio-item').removeClass('on');
      });
    

    DEMO

    Login or Signup to reply.
  2. When you click your minus it removes the class on. However, at the same time, as minus is located within portfolio-item, it triggers its click event and applies this class back.

    You can use e.stopPropagation() to disable this behaviour.

    According to documentation, e.stopPropagation

    prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

    Here is the working JSFiddle demo. It looks awful, but demonstrates the functionality.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search