why is this jQuery code endlessly looping as soon as the line
//$('.'+triggerThisChild).trigger("click"); // this causes endless loop
is uncommented FIDDLE is here
jQuery code:
$('a.touchNav').on('click touchend', function (e) {
var fancy = this.className.indexOf('fancy') != -1;
var target = $(this).attr('target') == '_blank' ? true : false;
if (fancy) {
var triggerThisChild = $(this).children('span').attr('class');
alert(triggerThisChild);
e.stopPropagation();
//$('.'+triggerThisChild).trigger("click"); // this causes endless loop
//return false;
} else if (target) {
window.open(this.href,target);
return false;
} else {
window.location = this.href;
return false;
}
});
$(".showFancyBox").fancybox({
"width" : "75%",
"height" : 800,
"transitionIn" : "none",
"transitionOut" : "none",
"type" : "iframe",
'href' : "http://www.google.com"
});
HTML:
<li>
<a class="touchNav" href="http://www.google.com" target="_blank">
Nav Point 1
</a>
</li>
<li>
<a class="touchNav" href="http://www.stackoverflow.com" target="_blank">
Nav Point 2
</a>
</li>
<li>
<a class="fancy touchNav" href="#">
<span class="showFancy0" style="display:none;"></span>
Nav Point 3
</a>
</li>
jQuery click trigger event handling system is a wrapper over native browser events. Because jQuery retains a reference to an event handler when it is introduced using on click function, it can be activated using jQuery’s trigger (“click”) command. Additionally, the JavaScript within the onclick attribute will be triggered.
The .trigger () method can be used on jQuery collections that wrap plain JavaScript objects similar to a pub/sub mechanism; any event handlers bound to the object will be called when the event is triggered. Note: For both plain objects and DOM objects other than window, if a triggered event name matches the name of a property on the object, ...
To trigger handlers bound via jQuery without also triggering the native event, use .triggerHandler() instead. When we define a custom event type using the .on() method, the second argument to .trigger() can become useful.
The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event. For example, consider the HTML:
The click event on .showFancy0
bubbles up to the parent a
and the whole thing runs again.
Add this code to stop it happening...
$(".showFancy0").on("click", function(e) {
e.stopPropagation();
});
Working fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With