Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore Parent onClick event when Child element is clicked

Please see - http://www.bootply.com/dR7fxjP1bk

By clicking any of the div.rows (lets call this parent), an onClick event is activated, for demo purposes an alert pops up.

Within the row an accordion collapses when the "info" (orange button) is clicked (lets call this child), but the problem is that the parents alert triggers.

I need the info button not to trigger the alert, only when anywhere else is clicked the alert appears.

I've tried various ways such as using (e)stopPropagation .on .off calls etc... I'm not the best jquery guy so need a little help getting this to work - and also help me learn something!

<div class="row ticket-selector" onclick="alert('Hello World!');">
    <a data-toggle="collapse" data-parent="#ticket-panel" href="#collapseOne" class="tickets-more"><span class="halflings info-sign orange"></span></a>
</div>

The above is the jist - but see for better understanding - http://www.bootply.com/dR7fxjP1bk

like image 944
Tom Rudge Avatar asked Sep 26 '14 13:09

Tom Rudge


People also ask

How do you stop event propagation from parent to child?

stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

How do I stop click event propagation?

To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.


1 Answers

The idea is to remove onclick="" handler saving its value in another field and then to execute (evaluate) value in custom click event handler:

Example code.

$(document).ready(function()
{
    var elements = $(".ticket-selector");
    elements.each(function()
    {
        var handler = $(this).attr('onclick');
        $(this).data('click', handler);
    });
    elements.attr('onclick', '');
    elements.click(function(e)
    {
        if (!$(e.target).hasClass("info-sign"))
        {
            eval($(this).data('click'));
        }
    });
});
like image 175
Regent Avatar answered Sep 30 '22 13:09

Regent