Search code examples
jqueryhtmlajaxevent-handlingjquery-steps

Click Handler can't find the target button


I used the click handler to perform the request when I click the button. This event works well when the button is located outside of the slider. As well if I apply the click event at slider. I tried many ways to make it work but still without understanding what could be causing this.

Could a jquery script like jquery steps influence another jquery script ?

HTML:

<div id="main">
<div id="slider">

    <h3>1</h3>
    <section>
        <p id="head">I'm using JQuerySteps.</p>
        <p id="body"><button type="button">Here is the button.</button></p>
    </section>

</div>
</div>

jQuery:

$("button").click(function(){

    $("#main").load("get.php", function(responseTxt, statusTxt, xhr){

    });

});

Problem: When I try to click the button while it's inside the jquery steps(#slider), the click handler doesn't work.

I'm sure this question sounds pretty stupid, but I'll appreciate any short advice or tip. Thanks in regards, Vladimir.


Solution

  • This is going to create a click handler on the matched element:

    $("button").click(function(){
        // ...
    });
    

    However, this is going to remove that element from the DOM (and I assume replace it with another similar one?):

    $("#main").load();
    

    The original button is now gone, and so is its click handler. So clicking the new button will do nothing because it has no handler.

    Instead of attaching the handler directly to the (short lived) button, attach it to a common parent element and filter on the button. Something like this:

    $(document).on('click', '#body button', (function(){
        // ...
    });
    

    That way the handler itself is attached to a non-changing element (in this case document, though any non-changing hierarchical parent element will do) so the handler function doesn't get lost. This is called event delegation.