MooTools event listener disappears after element.innerHTML is changed

Posted by acoder on Stack Overflow See other posts from Stack Overflow or by acoder
Published on 2010-05-17T22:15:31Z Indexed on 2010/05/17 22:20 UTC
Read the original article Hit count: 222

Filed under:
|
|
|

Hi everyone, I am trying to achieve this task using MooTools.

Description:

I attached an event listener to "myButton" link. A click on this link initiates an AJAX request and updates "myDiv" content based on the response text.

During this request a POST variable is being sent to "button.php", but it's not used at the moment..
(i wish to use it later)

OK, as a result, "myDiv" gets exactly the same link with the same ID (myButton) + a random number, so that we could see that each click generates a new number.

The problem:

After the first click on "myButton", "myDiv" updates correctly, showing a random number. When I click "myButton" for the second time (this time in newly updated div), the div does not refresh anymore.

Please note that I need "myButton" to be inside "myDiv", and "myDiv" must be updated (refreshed) after each click without having to refresh the entire page.

Can somebody show me how to achieve this task based on this simplified code example?


index.html

<html>
<head>
<script type="text/javascript" src="mootools-1.2.4-core-nc.js"></script>
<script>
window.addEvent('domready', function() {
  $('myButton').addEvent('click', function(e) {
    e.stop();
    var myRequest = new Request({
      method: 'post',
      url: 'button.php',
      data: {
        action : 'test'
      },
      onRequest: function() {
        $('myDiv').innerHTML = '<img src="images/loading.gif" />';
      },
      onComplete: function(response) {
        $('myDiv').innerHTML = response;
      }
    });
    myRequest.send();
    $('myButton').removeEvent('click');
  });
});
</script>
</head>
<body>
  <div id="myDiv">
    <a id="myButton" href="#">Button</a>
  </div>
</body>
</html>

button.php

<a id="myButton" href="#">Button</a> clicked <?php echo rand(1,100); ?>

© Stack Overflow or respective owner

Related posts about mootools

Related posts about events