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?
+4
A:
<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.)
Matchu
2010-03-01 21:28:57
Thankyou! Perfect
JimBo
2010-03-01 21:30:27
might want to add a note about the pre-conditions for when the script should run i.e. when the element exists in the DOM
Russ Cam
2010-03-01 21:32:41
Good catch - order switched, expanded.
Matchu
2010-03-01 21:35:36
Russ Cam
2010-03-01 21:46:13
might also want to add in some code to ensure that a function assigned to `onclick` already is not overwritten by assigning a new event handler... perhaps take a look at Dean Edward's addEvent library? - http://dean.edwards.name/weblog/2005/10/add-event/ or a variation on it
Russ Cam
2010-03-01 21:56:01
I'll let the OP handle that if he really needs it - but thanks! :)
Matchu
2010-03-01 22:38:32
I'm really not sure why people are upvoting the idea of avoiding jQuery and relying on a getElementById when there are so many known issues with this singular approach to getting things from the DOM, especially since the format that is being used to reference a FORM element above is known to not be a good practice: http://www.javascripttoolbox.com/bestpractices/
Nissan Fan
2010-03-01 22:52:59
+1
A:
You would be best to leverage jQuery for this. It's easy to learn and easy to use.
Nissan Fan
2010-03-01 21:30:27
Unless the OP wants to do something complicated, I think jQuery would be overkill.
Javier Badia
2010-03-01 21:31:42
Jquery is definetly not overkill since it will take care of multi-browser issue for the most part
MLefrancois
2010-03-01 21:33:17
getElementById will not work the same in all browsers. For example, in IE8 it's case sensitive and in prior versions it's not W3C compliant and has all types of known issues. It's not just IE that's problematic however. There's logic in your statement about less is more, but jQuery is a layer that ensures compatibility across user agents and is well worth leveraging.
Nissan Fan
2010-03-01 21:35:00
Unobtrusive JavaScript I agree, jQuery necessarily for this case only, I don't.
Russ Cam
2010-03-01 21:53:04