Javascript onclick event

I am very new to javascript. I know that you can add the onclick = "event to the html element ... but is it possible in javascript itself to declare that when someone clicks on the x element, the event fires?

+5
source share
2 answers
<input id="myElement" type="button" value="Click me!" />
<script type="text/javascript">
    document.getElementById('myElement').onclick = function () {
        alert('Hello, world!');
    }
</script>

Make sure that you either run this after the element already exists (the scripts below), or when the DOM is ready. (You can use it window.onloadfor this, but you can just use jQuery from the very beginning to, by the way, get the DOM-ready magic function. It onloadhas some drawbacks, such as waiting for images to load.)

+4
source
+1

All Articles