Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click button when user clicks in parent div

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/

like image 294
Genaut Avatar asked May 25 '26 11:05

Genaut


1 Answers

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>
like image 182
ravichandra reddy Avatar answered May 27 '26 02:05

ravichandra reddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!