Question

I seem to have run into a bit of trouble this morning with removeClass. First I click a div to add Class 'containerhover', then when I click the close button it will not remove the class that it has just added to the div.

I don't know if this has something to do with it being added to the dom only and not being actually coded into the HTML. Please can someone help.

HTML

<div class="container"></div>

jQuery

$(function() {

    $('.container').click(function(e) {
        var mythis = $(this);
        mythis.addClass("containerhover");
        mythis.find('.backface').addClass("bfhover");
        mythis.find('.album').addClass("ahover");
    });

    $('.closealbum').click(function(e) {
        $('.container').removeClass('containerhover');
    });
});
Was it helpful?

Solution

Use .on(), to attach the event to the container, and activate it only if the .closealbum element is clicked. Also, add the event.stopPropagation() method to prevent the event from bubbling further:

$('.container').on('click', '.closealbum', function(e) {
    $('.container').removeClass('containerhover');
    e.stopPropagation();
});
  1. Your problem is caused by the fact that the .closealbum element does not exist when binding the click event.
  2. Your element is positioned inside the other element. Without e.stopPropagation(), the event bubbles up, and the first event will also be triggered, undoing the second event's removeClass.

Demo: http://jsfiddle.net/knCR8/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top