I have two divs with dynamic links that sometimes are populated and sometimes aren't. If you a click a link that looks like this:
<a href="#">
Nothing happens, I prevent the default action, but if the link is:
<a href="/path/to/a/page">
It will follow.
I want to able to click on the surrounding div, and using the same logic as above. So if I click on the red and there is a valid link the link will follow. I'm using trigger()
to attempt this.
The situation is below:
$(function() {
$(".container").click(function(e) {
var clickTarget = $(e.target).attr("href");
var clickTargetLink = $(this).find(".container-link");
if ((clickTarget != "#") || (clickTarget != undefined)) {
clickTargetLink.trigger("click");
} else {
e.preventDefault();
}
});
});
.container {
padding: 50px;
margin-bottom: 1rem;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<a class="container-link" href="google.com">link</a>
</div>
<div class="container">
<a class="container-link" href="#">link</a>
</div>
What ends up happening is clicking on the red div with google.com in the link throws:
jquery.js:3988 Uncaught RangeError: Maximum call stack size exceeded at String.replace () at camelCase (jquery.js:3988) at Data.get (jquery.js:4069) at HTMLDivElement.dispatch (jquery.js:5146) at HTMLDivElement.elemData.handle (jquery.js:4991) at Object.trigger (jquery.js:8249) at HTMLAnchorElement. (jquery.js:8327) at Function.each (jquery.js:354) at jQuery.fn.init.each (jquery.js:189) at jQuery.fn.init.trigger (jquery.js:8326)
Maximum call stack size exceeded error - this suggests that there is an infinity loop somewhere in this code. I'm lost as to how that could be the case here?
Why is this code causing a maximum call stack size error?
EDIT: more research led me to: Maximum call stack size exceeded on trigger click
going
.triggerHandler()
just renders nothing and the link doesn't follow. Is there a different action I need to use that I'm not aware of?
EDIT #2: a few more details:
- I cannot change/add markup structure.
- the red div needs to be fully clickable, as there is another action tied to it when the link is empty:
<a href="#">
- I tried
e.stopPropagation();
- which resolves the error, but then the link doesn't follow - I tried
triggerHandler()
- http://api.jquery.com/triggerhandler/