JimBo
JimBo

Reputation: 313

onclick event in the javascript

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

Upvotes: 5

Views: 342

Answers (3)

Hellcodes.js
Hellcodes.js

Reputation: 49

Quite possibly the best method is event listeners

<button id="x">click on me</button>
<script src="main.js">
    const button = 
    document.getElementById("x");
       
    button.addEventListener("click" () => {
    alert("hello world")
})
    /*
    it might not be as good in small 
    projects, but in large ones, this 
    saves a ton of time.
    */
</script>

Upvotes: 1

Matchu
Matchu

Reputation: 85862

<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 (scripts at the bottom), or when the DOM is ready. (You could use window.onload for that, but you might just want to use jQuery from the beginning so that, among other things, you get a magical DOM-ready function. onload has some downsides, like waiting for images to load.)

Upvotes: 5

Keith Adler
Keith Adler

Reputation: 21178

You would be best to leverage jQuery for this. It's easy to learn and easy to use.

http://api.jquery.com/click/

Upvotes: 1

Related Questions