Results 1 to 3 of 3

Thread: MooTools: Problem with click event.

  1. #1
    Join Date
    Mar 2006
    Posts
    41
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default MooTools: Problem with click event.

    I have an AJAX routine that calls a script that generates content that is dynamically => <div id="testdiv">inserted</div>.

    I want to trap a click event:
    [code=text]
    $('testdiv').addEvent('click', function(){
    alert('Hello');
    });
    [/code]
    But I'm getting an error message: 'null' is null or not an object

    It works fine for hard coded code, but not code in the dynamically populated DIV.

    Why? Workaround?

  2. #2
    Join Date
    Sep 2005
    Location
    India
    Posts
    1,625
    Thanks
    6
    Thanked 107 Times in 107 Posts

    Default

    It seems that you are executing the code that you've furnished in your post before the div element whose Id is 'testdiv' comes in the DOM. In other words the first step should be to insert the

    Code:
    <div id="testdiv"></div>
    After this part only you should invoke the following code:

    Code:
    $('testdiv').addEvent('click', function(){
    alert('Hello');
    });
    Otherwise what happens is you are trying to add an onclick event on an element which does not exists with the mentioned ID. If the element does not exists you can't attach events to it.

    Hope this helps.

  3. #3
    Join Date
    May 2008
    Posts
    144
    Thanks
    6
    Thanked 11 Times in 11 Posts

    Default

    change this:
    Code:
    $('testdiv').addEvent('click', function(){
    alert('Hello');
    });
    to this:
    Code:
    window.addEvent('domready', function(){
    $('testdiv').addEvent('click', function(){
    alert('Hello');
    });
    });

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •