Why does listener activate twice?

87 views Asked by At

I have the following html:

<ul id="all-terminals">

        <li data-terminal-id="101" class="">
            <label>
                <input type="radio" name="terminal" class="all" data-terminal-id="101">
                <a ...></a>

               ...
            </label>
        </li>

        <li data-terminal-id="100" class="active">
            <label>
                <input type="radio" name="terminal" class="all" data-terminal-id="100">
                <a ..></a>

               ...
            </label>
        </li>

        <li data-terminal-id="102" class="">
            <label>
                <input type="radio" name="terminal" class="all" data-terminal-id="102">
                <a...></a>

              ...
            </label>
        </li>
    </ul>

I wrote the following listener:

$(document).on('click', '#all-terminals li label', function(){alert(123)});

when I click on label, I see that alert executes twise.

Why?

4

There are 4 answers

0
KidBilly On BEST ANSWER

Not exactly sure why, but mouseup works.

$(document).on('mouseup', '#all-terminals li label', function(){alert(123)});
2
Ashok Mandal On

I think bubbling is occurring in your case . Read about on Bubbling and Capturing

2
James McDowell On

I'm not completely sure, but I think that when you click on the label, you hit 2 of its child overlapping elements. Because they are part of the label but still separate elements, it fires two click events on label.

On the fiddle, it appears the it's the [a] element overlapping the ...

3
Rick Hitchcock On

Clicking a label automatically creates a click event on an input within it.

Assuming all your labels have inputs, you can simply change to:

$(document).on('click', '#all-terminals li input', function(event) {
  alert(123);
});

Fiddle