0

How do I bind an html event such as onclick to a function myFunc(e){}?

I do not want to use document.getElementByClass or Id.

I do not want use jQuery.

4
  • You want your click to trigger a function? Commented Nov 19, 2017 at 4:52
  • Yes. Click would be great. Just curious about the (e) event and binding somehow. Commented Nov 19, 2017 at 4:56
  • There are a lot of SO where you can get what you want to do. Commented Nov 19, 2017 at 4:59
  • Possible duplicate of onclick event handler in javascript code, not html tag Commented Nov 19, 2017 at 5:01

3 Answers 3

1

Try this:

document.getElementsByTagName('body')[0].addEventListener('click', function(){alert("you clicked on the page")})

This adds an event listener to the body tag. Once you click on the page, it will fire the alert function.

You can get the elements by either class name, id and/or tag name:

document.getElementById('someId')
document.getElementsByClassName('someClassName')  
document.getElementsByTagName('body')

Keep in mind, the "getElementsByClassName" and "getElementsByTagName" return arrays, so you might want to add the index like this

getElementsByTagName('body')[0]
document.getElementsByClassName('someClassName')[1]
...
Sign up to request clarification or add additional context in comments.

Comments

0

If it's still the 1990s where you are and jQuery hasn't been invented, then sure:

<div onclick="myFunc">
</div>

2 Comments

Lol. Thanks for the help
It's the simplest thing that works without jQuery. Don't knock it!
0

First you must find the element on the page, for example var element = document.getElementById('clickme'), then you must add a listener to the click event element.addEventListener('click',function)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.