26

After the request, the new elements created are not recognized by the event handlers in my jQuery code.

Is there a way to reload the file to re-register these events?

3
  • please improve your problem definition. This does not suggest anything useful!! Commented Dec 21, 2011 at 18:20
  • When you say "not recognised by jQuery", are you talking about event handlers not being called? Commented Dec 21, 2011 at 18:25
  • 1
    Now that you have the correct answer, please edit your question to improve it, so that when other people with the same issue find it, they will understand that this question applies to them. Commented Jan 5, 2012 at 23:26

10 Answers 10

22

I'm assuming that you mean that events you've registered for elements that have been replaced by with the results of your ajax requests aren't firing?

Use .live() (see http://api.jquery.com/live/) to register the events against elements that the match the selector (including the new DOM elements created from the results of the ajax), rather than the results of the selector when the event handlers were first, which will be destroyed when they are replaced.

e.g. replace

$('div.someClass').click(function(e){
    //do stuff
});

with

$('div.someClass').live('click', function(e){
    //do stuff
});

Important:

While I've recommended using .live() this is for clarity as its syntax is similar to .bind(), you should use .on() if possible. See links in @jbabey's comment for important information.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for debugging the question and coming up with what is probably the correct answer.
while live() still works, you should be using delegate() for jQuery 1.4.3 - 1.6.4 and on() for 1.7+ api.jquery.com/delegate api.jquery.com/on
Yes that's the problem. After the request I create new bloc with class="result" but after jquery does not detect any event on these new block. I will look .live() thanks
@jbabey +1 Absolutely, seeing the difference between bind and live will make the (potential) problem easier to understand for the OP. Added reference to your comment and explaination.
18

This question was about binding event handler on DOM element created after the loading of the page. For instance, if after a request ajax you create a new <div> bloc and want to catch the onClick event.

//This will work for element that are present at the page loading
$('div.someClass').click(function(e){
    //do stuff
});

// This will work for dynamically created element but is deprecated since jquery 1.7
$('div.someClass').live('click', function(e){
    //do stuff
});

// This will work for dynamically created element
$('body').on('click', 'div.someClass', function(e){
    //do stuff
});

You would find the documentation here: http://api.jquery.com/on/

Comments

5

This codes works perfect for me..

$("head script").each(function(){
            var oldScript = this.getAttribute("src");
            $(this).remove();
            var newScript;
            newScript = document.createElement('script');
            newScript.type = 'text/javascript';
            newScript.src = oldScript;
            document.getElementsByTagName("head")[0].appendChild(newScript);
        });

It removes the old script tag and make a new one with the same src (reloading it).

3 Comments

Hi!!! this is nice and what i need but where I will put it to execute after my ajax response.
Thanks its perfectly working but takes long time to process request....suggest if there any improved way to reload whole js in same way
I have an script where you can drag and drop to order things. My problem was it was not refreshing after aJax call for another script using aJax on the draggable elements. Tried everything but this helped me out a lot! I had to alter things slightly, but resolved my issue, can't thank you enough!
3

To increase the website performance and reduce the total file’s size return, you may consider to load JavaSript (.js) file when it’s required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.

For example,

$("#load").click(function(){
    $.getScript('helloworld.js', function() {
        $("#content").html('Javascript is loaded successful!');
    });
});

when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.

Try it yourself In this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.

<html>
<head>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

</head>
<body>
  <h1>Load Javascript dynamically with jQuery</h1>

<div id="content"></div>
<br/>

<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>

<script type="text/javascript">

$("#load").click(function(){
  $.getScript('js-example/helloworld.js', function() {
     $("#content").html('
          Javascript is loaded successful! sayHello() function is loaded!
     ');
  });
});

$("#sayHello").click(function(){
  sayHello();
});

</script>
</body>
</html>

Comments

1

In your request callback, call a function that acts on your newly appended or created blocks.

$.ajax({
   success: function(data) {
        $('body').append(data);
        //do your javascript here to act on new blocks
   }
});

Comments

1

simple way to solve this problem

$(document).ready(function(){

$('body').on('click','.someClass',function(){

//do your javascript here..

});
}); 

Comments

1

You can also attach the click handlers to the body so that they never get destroyed in the first place.

$('body').on('click', 'a', function(event) {
  event.preventDefault();
  event.stopPropagation();
  // some stuff
})

Comments

0
  var scripts = document.getElementsByTagName("script");
  for (var i=0;i<scripts.length;i++) {
    if (scripts[i].src)
      if(scripts[i].src.indexOf('nameofyourfile')  > -1 )
        var yourfile = scripts[i].src;
  }
  jQuery.get(yourfile, function(data){
  if(data){
     try {
      eval(data);
     } catch (e) {
     alert(e.message);
    }
 }
    });

Comments

0

You can try loadscript plugin for loading the javascript file.

forexample 
$("#load").click(function(){
    $.loadScript('path/example.js');
});

or 
$.ajax({
   success: function(data) {
        $.loadScript('path/example.js');
   }
});

http://marcbuils.github.io/jquery.loadscript/

Comments

-1

What do you mean not recognized by jQuery?

jQuery walks the DOM each time you make a request, so they should be visible. Attached events however will NOT be.

What isn't visible exactly?

P.S.: Reloading JavaScript is possible, but highly discouraged!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.