I have this code for some elements in my web that I want to do this:
When user clicks in a div, trigger a click on the button inside div (in this case, these buttons open a modal), This works in other places in the page where I make a window.location instead a trigger. What is bad with this code? I dont know it :(
Sorry my english, thanks.
jQuery(".hover-content").click(function(e){
var hl = jQuery(this);
jQuery(this).find("button").each(function(){
if(jQuery(this).is(":visible")){
jQuery(this).trigger("click");
}
});
});
Console shows this error:
Uncaught RangeError: Maximum call stack size exceeded
Little example: https://jsfiddle.net/z0704nss/
It's because of event bubbling in Javascript.
I'm able to replicate and resolve it by using adding e.stopPropagation() to your piece of code.
$(".hover-content").click(function(e){
e.preventDefault();
console.log('hi')
e.stopPropagation();
$(this).find("button").each(function(){
if($(this).is(":visible")){
$(this).trigger("click");
}
});
});
$('.button-ex').click(function(e){
e.preventDefault();
e.stopPropagation();
console.log('clicked button')
})
body {
background-color: #eef;
padding: 5px;
}
.hover-content{
background-color:#FF0000
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="hover-content">
<button id="btnOne" class="button-ex">demo1</button>
<button id="btnTwo" class="button-ex">demo2</button>
</div>
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