raivis
raivis

Reputation: 37

JavaScript mootools addEvent

I am trying to find what's wrong with my code. Mootools core file is attached to HTML head and works well.

If I add the code:

$('myElement').addEvent('click', function(){
    alert('clicked!');
});

right below the <div id="myElement">Click me</div> then it works.

But if I add it to the separate javascript.js file then it does not work

HTML is this:

<!DOCTYPE html>
<html>  
<head>   
<script type="text/javascript" src="mootools-core-1.4.5-full-nocompat.js"></script>
<script type="text/javascript" src="javascript.js"></script>  
</head>
<body>  
<div id="myElement">Click me.</div>
</body>  
</html>

And javascript.js is this:

$('myElement').addEvent('click', function(){
    alert('clicked!');
});

All files (html, mootools-core and javascript.js are in the same directory). Any ideas?

Upvotes: 3

Views: 1880

Answers (1)

Rob W
Rob W

Reputation: 348992

You have to wrap the expression in a domready event:

window.addEvent('domready', function() {
    $('myElement').addEvent('click', function() {
        alert('clicked!');
    });
});

Upvotes: 6

Related Questions