Problem with event.stopPropagation () & onClick (jQuery)

I wrote this part of the code a few years ago, and at that time it worked in FF and Chrome, but now it leads to an endless loop in Chrome.

<script> function clickChildLink(el, event) { console.log('inside function'); var evtTarget = $(event.target); if (evtTarget.is('a')) { console.log('returning'); return; //ignore clicks if its a link } $(el).children('a').click(); } </script> <div onclick="clickChildLink(this, event);"> <a href="#" onclick="console.log('before'); event.stopPropagation(); console.log('after'); return false;">Header</a> </div> 

You can run the code here: http://jsfiddle.net/Py7Mu/205/

Basically, what he should do is if the user clicks inside the div (i.e. the title), he finds the link inside it and causes a click on it. In Chrome, this triggered click also propagates back to the parent, who, in turn, starts the whole process again.

I know that I should use less intrusive javascript, but this comes from the old rails application (update hopefully coming soon).

Any idea why the event doesn't actually stop propagating? Technically, the code should work without calling stopPropagation, since the if statement inside the function should stop subsequent calls from firing. Chrome doesn't seem to update currentTarget on click soft call

+4
source share
2 answers

if there is only one child anchor, you cannot just do something like ...

 $(el).click(function(){ if (this.tagName !== 'A') this.getElementsByTagName('A')[0].click(); }); 

or I think if it is nested further ...

 $(el).click(function(){ if (this.tagName !== 'A') $('a', this)[0].click(); }); 
0
source

This seems to be caused by the handling of inline event handlers. If you attach them using jQuery, onDomReady, it should work and, even better, a cross browser (your current script will not work in IE and 9). In addition, you do not need a binding check inside the event handler if you can stop the propagation correctly.

Try the following:

 $(function(){ $(div).click(function(){ $(this).children('a').click(); }); $(a).click(function(e){ e.stopPropagation(); }); }); 
0
source

Source: https://habr.com/ru/post/1387326/


All Articles