Search code examples
jquerystoppropagation

jQuery: Function is called twice. Propagation? Why does this happen?


Please take a look at the following fiddle: http://jsfiddle.net/K9NjY/

I've spend 3-4 hours on this code and I've narrowed it down to the shortest version and now I'm stuck.

Problem: 1. Click 'divOne' 2. Click switch DivNames 3. Click 'divTwo'

*Why is divOne still being alerted? How do I stop this? * Logic would tell me that when we click divTwo we should only get one alert that says 'divTwo'

Notice that doSomething() has a function that's triggered by a click inside it. This cannot change i.e. $("." + divName).click(function(){...}); must remain inside doSomething()

What can I do about this?


Solution

  • Remove the event listeners using off and add again, switching the class names won't unbind existing event listeners -

    function doSomething(divName){
    
        $(".action").off().addClass(divName).html(divName).click(function(){
            alert(divName);
        });
    }
    

    FIDDLE