Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 506
raivis Avatar asked Mar 22 '26 09:03

raivis


1 Answers

You have to wrap the expression in a domready event:

window.addEvent('domready', function() {
    $('myElement').addEvent('click', function() {
        alert('clicked!');
    });
});
like image 172
Rob W Avatar answered Mar 24 '26 23:03

Rob W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!