PDA

View Full Version : MooTools: Problem with click event.



JBottero
08-30-2009, 11:03 PM
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:


$('testdiv').addEvent('click', function(){
alert('Hello');
});

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?

codeexploiter
08-31-2009, 12:21 PM
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


<div id="testdiv"></div>

After this part only you should invoke the following 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.

thenajsays
08-31-2009, 12:28 PM
change this:

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

window.addEvent('domready', function(){
$('testdiv').addEvent('click', function(){
alert('Hello');
});
});