0

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.

  • 1) It's not very clear in what way this isn't working, can you elaborate? 2) Not sure if this is the problem or just an observation, but as soon as that `.load()` executes it's going to remove all of the button click handlers. You might want to attach the click handler to `document` and filter on `button` using `.on()` if the elements are going to be dynamically removed/added like that. – David Feb 18 '15 at 19:56
  • The slider dont have another click event attached? maybe the first click event is launched and not the second – Jesús Quintana Feb 18 '15 at 19:56
  • Just updated with the problem, Thanks David, I'll research on this, I just needed some points to investigate it. –  Feb 18 '15 at 20:03
  • I think you may be binding an event to an unavailable element. Try this: `$("#slider").on('click', 'button', function(){...your function stuff here` – Ted Feb 18 '15 at 20:05
  • You're right Ted, it works well now. thanks –  Feb 18 '15 at 20:10

1 Answers1

1

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.

David
  • 208,112
  • 36
  • 198
  • 279
  • This worked man! I'll make a little dance, take some notes and proceed on this project. thanks –  Feb 18 '15 at 20:14