Does onclick() have to be coded in the HTML?

Hello,

I was wondering if when handling onclick events for buttons, do you have to put the onclick code in the HTML:

<input id=“generateButton” type=“button” value=“Generate Table” onClick="generateTable()">

Or is there a way to handle it all in the javascript and just leave the HTML like this:

<input id=“generateButton” type=“button” value=“Generate Table”>

Thanks

It is preferable that JavaScript is completely separate from HTML being placed in the head or end of the body externally linked.

in the simplest form


window['onload'] = function() {
   var button = document.getElementById('generateButton');
   button['onclick'] = function() { alert('click'); };
};

If you spell it with a capital C then it MUST go in the HTML because only where it is in the HTML can the capitalisation be corrected so as to reference the correct event handler (which is called onclick). If you spell it onClick in your JavaScript then JavaScript will assume that you are referencing a new variable since there is nothing in JavaScript by that name.

As oddz says, it is better to not place JavaScript inside the HTML and so onClick should never be used anywhere.

Do you know of any tutorials or writings that can show me the basics to handling events this way using only the external java script file? In school I was only taught how to do the events in the html tags themselves.

Hi shaner217,

You almost never need to put any javascript in your HTML and should as a general rule put almost all your javascript in one or more separate files imported in your header. Assuming you’ve included jQuery you can write something like:

${“input”).click(function() { do something });

You should think twice about using the click listener though as many people will not navigate the form using a mouse. I personally navigate most forms using tab and enter. If you want something to happen on form submission, and again you use jQuery you could do:

$(“form”).submit(function() { do something });

Oh, and if you want a good tutorial, check out:

http://docs.jquery.com/Tutorials:How_jQuery_Works

I prefer to put the onclick in the html provided it has only 1 line of js code in it…eg…calling a function or assigning a value to a variable etc.

Putting the event handler in the html makes it easier for me to see what events are attached to an element rather than going looking for them through an external javascript file.

Regarding adding an onlick event handler to an element using javascript, I normally do something like this.

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
 
window.onload=function() {
     var imgO = document.getElementById("imgMyPic");
     imgO.onclick = function() {
           alert('Image was clicked');
     }
}
 
</script>
</head>
<body>
 
<div>
       <img id="imgMyPic" src="pic1.jpg" alt="" />
</div>
 
</body>
</html>

Thanks so much.

Can you explain what the purpose of “function()” is? I assume it just means “This event does this function” but I’m used to seeing uniquely named methods. As you can tell I’m not very experienced with JS.

Can you have:

imgO.onclick = [I]methodname/I

and then define the method somewhere else? I feel so uneducated asking these questions but oh well.

Thanks for your help!

yes, the .onclick=function() {
//some code
}

simply means add the code in between the {} to the onclick property of the element.

yes, you could also have had

 
<script type="text/javascript">
 
function myFunction() {
     alert('Image was clicked');
}
 
window.onload=function() {
     var imgO = document.getElementById("imgMyPic");
     imgO.onclick = myFunction;
}
 
</script>

function() is the best of the three ways to define a function because it provides the most flexibiility with the least overhead.

Just as an update, the click event does not have this problem as it is also triggered by keyboard controls too.

Yes you can. The onload technique is not even required these days because you can place your script just before the </body> tag, which loads your script before the onload event.

Here’s the code updated to show this technique:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
    <img id="imgMyPic" src="pic1.jpg" alt="" />
</div>
<script type="text/javascript">
function myFunction() {
     alert('Image was clicked');
}

var imgO = document.getElementById("imgMyPic");
imgO.onclick = myFunction;
</script>
</body>
</html>

I stand corrected :slight_smile:

[QUOTE=pmw57;4738761]Yes you can. The onload technique is not even required these days because you can place your script just before the </body> tag, which loads your script before the onload event.]

I would still advise against putting your script inside your HTML for the same reason I would advise against putting your CSS inside your HTML.

It’s a slippery slope. It seems fine to start with because YOU know you’re only going to do it a once or twice, but then cut and paste sets in and you end up with inline code all over the shop. Keep it separate whenever you can, it’s just good form.

I tend to agree with goldfidget on this one though of course where you put javascript is a personal choice.

Imho it is better to keep javascript out of the html, except perhaps in single lines of codes calling a function or whatever in event handlers. The javascript is better kept in external files so they can be used by other pages if required and in cases where you have javascript specific to one page only, I would recommend putting it in the <head>.

[QUOTE=goldfidget;4739728I would still advise against putting your script inside your HTML for the same reason I would advise against putting your CSS inside your HTML.[/QUOTE]

To clarify, I do not mean that you should place inline code at the end of the body.


<body>
...
<script type="text/javsacript">
(function () {
    ...
}());
</script>
</body>

What I actually mean is that you should link to your script from the end of the body instead.


<body>
...
<script type="text/javsacript" src="js/script.js"></script>
</body>

just out of curiosity, why would you prefer doing that as opposed to loading your javascript in the <head>.

First loading in the head means that you cannot attach events on to page elements. Any scripts up there must wait until the body has loaded, by using an onload event, or if you’re lucky, a domcontentready event. The upshot of this is that the head code has to wait even longer than the code that’s at the end of the body.

Second, when the web browser comes across a script it must stop and wait until the complete script has been loaded, and executed, before it can carry on. This slows down the apparent loading speed of your page. When you move the scripts to the bottom, the page content appears sooner, helping to provide the illusion of a faster loading web page.

There are some best practices for speeding up your web site. One of these best practices is to put [url=“http://developer.yahoo.com/performance/rules.html#js_bottom”]scripts at the bottom.

hmmmm…good points :scratch:

never really thought about it that way, in terms of speeding the loading of content.

so I guess that unless the js needs to be in the <head> (for scope issues for example) then linking to javascript files at the end of the <body> is actually better.

nice food for thought :slight_smile:

I hope that those scope issues aren’t for inline scripting events. There are some people who believe that such techniques belong to the 20th century. And should stay there! :slight_smile: