Given the following jQuery function.
$(document).on("click", ".subMenu>a", function(event) {
$(this).closest("a").attr("href", "../public_resources/Category.jsf?id=5").trigger('click');
});
This function is called, when a <span> inside an <li> like as follows is clicked.
<li class="ui-widget ui-menuitem ui-corner-all ui-menu-parent subMenu" role="menuitem" aria-haspopup="true">
<a href="../public_resources/Category.jsf?id=5" class="ui-menuitem-link ui-submenu-link ui-corner-all" tabindex="-1">
<span class="ui-menuitem-icon ui-icon ui-icon-contact"></span><span class="ui-menuitem-text">Occassion</span>
</a>
</li>
As can be seen, the given jQuery function is mapped by a CSS class subMenu (in <li>). When this function is called (it is called, when an area enclosed by the <li> tag is clicked), the anchor tag is given a desired URL in this function which in turn, triggers a click event which causes the same function to be invoked once again - ultimately causing an infinite recursion with the following error.
Uncaught RangeError: Maximum call stack size exceeded
Is there any way to avoid this recursion, probably by rewriting the function somehow?
The HTML code given here is generated by a UI framework and it is very unlikely to touch it.
I could use window.location instead of using .trigger('click') but when a user click a sub menu by holding the ctrl key, for example, the page should be opened in a new tab. This does not happen by using window.location.
$(this).off('click').attr(...).trigger('click'), but I don't think triggering a click like that will cause the link to be followed. - Jason P