3

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/

Genaut
  • 1,810
  • 2
  • 29
  • 60
  • can you provide [Jsfiddle](https://jsfiddle.net/) example to work on it ? – Shady Alset May 01 '16 at 11:47
  • Try simply .click(); instead of .trigger("click"); – Fe Le May 01 '16 at 12:02
  • Yes, the problem aren't the trigger or click function, I am getting this error: Uncaught RangeError: Maximum call stack size exceeded We have 9 divs with 2 buttons in the page, I dont think this should be a stack problem :S – Genaut May 01 '16 at 12:04

1 Answers1

3

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>
Community
  • 1
  • 1
  • https://jsfiddle.net/9jq73ecf/ What about this? If you have 9 divs with these contents. All execute for each buttons. This example looks like the code that I have: https://jsfiddle.net/z0704nss/ (And same error) – Genaut May 01 '16 at 13:31