Search code examples
javascriptjquerybpopup

How to stop event bubbling in this code?


$('#div1').on('click', '#otherDiv1', function(event){       
        //Show popup
        $('#popupDiv').bPopup({
            modalClose: false,
            follow: [false, false],
            closeClass: 'close'
        });             
        event.stopPropagation();

        $('#div2').on('click', '#otherDiv2', function (event) { 

             // here is ajax request         

            // close popup          
            $('#popupDiv').bPopup().close();
            event.stopPropagation();
        });

    }

Click on otherDiv2 calls ajax function many times, how can I stop this?

HTML code

<div id="div2">

<div id="div1"><div id="otherDiv1">Click</div></div>

    <div id="popupDiv"><div class="close">X</div> 
        <input id="otherDiv2" name="otherDiv2" type="submit" value="Click" />   
    </div>
</div>

popupDiv is created dynamically

When I click on otherDviv1 the popup is open, inside is a button for ajax request. When I click button a request is called and popup closed. If I click one more time otherDiv1 and button a request is called two times and so on.

Thanks


Solution

  • Its not necessary to bind a second click within another click. Your code bind click to #otherDiv2 on each click to #otherDiv1. For following process don't need stopPropagation().

    $('#div1').on('click', '#otherDiv1', function(event) {
        //Show popup
        $('#popupDiv').bPopup({
            modalClose: false,
            follow: [false, false],
            closeClass: 'close'
        });
    });
    
    $('#div2').on('click', '#otherDiv2', function(event) {
    
        // here is ajax request         
        // close popup          
        $('#popupDiv').bPopup().close();
    });
    

    But If you need to bind event within another event then first unbind the event from #otherDiv2 and then bind again.

    $('#div1').on('click', '#otherDiv1', function(event) {
        //Show popup
        $('#popupDiv').bPopup({
            modalClose: false,
            follow: [false, false],
            closeClass: 'close'
        });
    
        $('#div2').off('click').on('click', '#otherDiv2', function(event) {
    
          // here is ajax request         
          // close popup          
          $('#popupDiv').bPopup().close();
       });
    });