Is it really bad form to use inline event handlers

I’ve been teaching myself javascript and I’m a bit confused about the whole events business. I’ve been reading the Sitepoint book (among a bunch of others) and when it gets to Ch 4 things get down right confusing. They claim that inline event handlers are “so 1998”, something I’ve heard before and then they proceed to write some pretty complex library files to get around the fact that IE <= 7 doesn’t support much of the alternative ways of handling events–a familiar enough story. Anyhow, it seems that many many tutorials all over the internet (and countless pages) resort to inline event handlers as the standard. So, I’m confused. I obviously need to know inline event handlers if I intend to work as a web developer even though it’s so 1998. Obviously inline even handlers are not quite on par with inline font attributes and transparent gif files despite the language one often hears. Can someone set me straight, and if possible suggest a brilliant tutorial, book chapter, or website that lays everything crystal clear for me?

IE6 up support event handling just fine. When I see inline JavaScript I think to myself one of two things:

a.) person has no idea what they are doing
b.) legacy code

I can understand the later but not the former.

It looks bad, to me it feels the same as when I see inline CSS.

I think that every webdesigner should respect the separation between content, presentation and behavior, and using inline JS breaks this rule (and it also makes the code less maintainable and more verbose, which should be enough to convince you not to use it).

Inline JS makes me cry. =p

While it’s good to learn Javascript down at the low level (like you are doing), which does require building up a bit of a library, in practice when working on larger projects it makes sense to use a framework or library like jQuery to do your Javascript. That really simplifies things.

However, in the same breath I’ll warn you to not just skip over the low level stuff and move straight to jQuery or the like because there are some things jQuery doesn’t do, because Javascript already does it quickly and easily. This means if you skip straight to jQuery, you won’t be able to do the simple things.

I have no intention of jumping over js to jQuery, since I understand the trap. Anyhow, if inline event handlers are out where can I find a brilliant tutorial or book chapter on how to deal with this part of js in a way more amenable to 2011. The Sitepoint book Simply JS I found pretty good until they got to that opaque chapter. I found Js the definitive guide great but too many little exceptions and details for a general understanding. Anyhow, any advice would be helpful. Many books and sites show the inline method, which, given how 1998 it is seems surprising but true.

Here’s a simple runnable demonstration of installing event handlers on elements.

The first function installs a mouseover handler that changes the element’s background colour.

The second function shows how to determine which nested element triggered the event.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Event Handlers</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type='text/css'>
img{border:2px solid #000}
#aDiv{ width:100px; height:100px; background-color:#00f }
</style>
</head>

<body>
<p>
 <div id='aDiv' ></div>
<p>
 <a href="#" id='lnk1'>### LINK #####
  <span id='sp1'>Span around
   <img id='img1' src='myPic1.gif' width='100' height='100' alt='Missing Image'>the image
  </span>### LINK #####
 </a>


<script type='text/javascript'> /* Always below the involved elements unless executed from nload handler */

/* Simple hover background colour change */

document.getElementById( 'aDiv' ).onmouseover = function()
{
  this.style.backgroundColor = '#f40' ;
}


/* Use the event object to determine and display which nested element triggered the mouseover event */

document.getElementById( 'lnk1' ).onmouseover = function( evt )
{
  var elem = ( elem = ( evt || window.event ) ).srcElement || elem.target;

  document.title = elem.id;
}

</script>

</body>
</html>

At least when the event handlers are inline you can see that there is already one attached when you need to attach more processing to the same event. Of course as soon as you add one to your JavaScript it will override the one in the HTML and be just as confusing as if you add two at different spots in the JavaScript.

I think what felgall meant is if you do something like an inline onclick, and then use Javascript to assign a click event elsewhere, the inline onclick is overridden and thus no longer used.

Also, what I meant by “low-level” stuff, I meant knowing how to actually affect things like “hide()” and “show()”, how to handle strings, etc., which jQuery kind of wraps up in a nice package for you.

Another reason to avoid inline Javascript is because you can move it to a separate file which only has to be loaded for your entire site, whereas if you have it inline it has to be loaded on every page.

Logic Ali, I would actually recommend that instead of putting your scripts right below the element, you put them in an onload function in your header, so they are hooked up after your page is finished loading. There are a few times you’d want to do it your way, but it’s better to consolidate your Javascript because it makes it MUCH easier to maintain (especially on large projects).

Here is an example:


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
window.onload = function() {
    document.getElementById('myLink').onclick = function() { 
        alert('hi');
    };
}
</script>
<body>
<p><a href="#" id="myLink">Click me</a></p>
</body>

Philosopher Dog, what you are reading for the most part is all still good. Pretty much anything you learn to attach in one place can be attached via any of the three methods (inline, in an inline script block, in a script block in the header).

If you just remember that it won’t work until it’s loaded you should be able to figure out which one you need to use and when.

That’s exactly what I meant. If you have one reference in the HTML and another in the JavaScript it will be really messy trying to work out why the one in the HTML isn’t working.

Even simpler is to put the JavaScript at the bottom where it will not delay the loading of the web page.


<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<body>
<p><a href="#" id="myLink">Click me</a></p>

<script type="text/javascript">
document.getElementById('myLink').onclick = function() { 
    alert('hi');
};
</script>
</body>

Hi there, I was just looking for the same issue…

I can’t really understand why or why not using inline event-handler - “no, no, never” confuses me totally…

For most cases I do agree. Binding an event-handler to several equal elements makes sense and ends up in “nice and less”-code.

But, how do you solve this.

Having a data-table with n rows, e.g. representing a user or whatever dataset.

Having 10+ columns which are representing subsets of detail-data.

Each table-cell (c) could represent more subsets of data. e.g a list of phone nrs., email-addresses, or or or. (x entry per cell)

And…each single cell entry (x/c) should be: view- (if more is behind it), edit- and deletable. (simple xhr call) (view-icon, edit-icon, delete-icon per c/x - no, no easy dropdown)

(Don’t ask why or what for - that’s what the customer wants)

So, I end up with at least either one event-handler, or one per row, or one per…I skip this…that part is not the question or problem.

But I have to “mark” every of the x/c cell entry’s with something like “What to do, Who am I” and definitely more (using attributes I think).

Assuming further more that I build the table on the server-side requested by a xhr-request - then I have to have a very “nice” client-side script… (ok, no problem with jQuery e.g.) …i could easily send a little js to call the binding function(s?). (or extend the response handler…, or whatever more)

Sounds like there is no real advantage in binding the events to that many different objects, isnt it?

I will end up with the same size of code (instead of "onClick=“f(xx,yy,zz)” I’ll have at least the same, or more attribute=“value1,value2,…” code + parsing, more)

Plus…I’ll end up with at least one potential source of error more…the binding function(s) on the client side.

So building the table and attaching to each element instantly a little inline event sounds soooooo easy for me.

Could someone enlighten me please?!

Regards,

Wolf

@felgall: Agreed. Even Yahoo recommends putting it at the bottom now. I recently wrote a Wordpress JS, CSS, and HTML optimizer plugin which has an option to place all JS in the footer. It’s just a new “technique” that I’ve just started using, so I forget about it. =p Thanks for bringing it up.

Great question, Wolfsblut.

There are several advantages for skipping inline events still. You are correct that if each one are entirely unique that they do have to each be labeled in some manner. However, most of the cases you’ll want to work in groups so it already makes sense to group them in some manner.

For example, say you have a table which has a column of numbers which you want to click to edit, a column of links which when clicked should open up a new window with that link in it, a column of images that when clicked should resize, a header row when clicked should sort that column, and then a few random cells which you want to restrict, just for the heck of it.

The simple method would be to put a class into each of these cells marking which ones they are. However, since there is a logical grouping, you can make use of that. You can use elements like the column and header elements to mark things, or you could get every n-th element in that row, or some other manner. Only the few odd ones out would need to be explicitly labeled.

Now you can perform operations on each of these. jQuery and the like make selecting these easier, but they don’t do anything that can be done with regular Javascript (since that’s what jQuery is, just with some added functions on top).

You can then put every last bit of your Javascript in one place, so you never “forget” you have something which makes debugging it two years later a tremendous pain. You also have a few other minor advantages like not having to worry about functions being called before they’re fully loaded (since they aren’t attached until it’s loaded), you get cleaner HTML, you don’t have to put function calls in multiple places, etc.

I won’t say that there aren’t those one off times when inline calls make sense, but even in those rare times I still prefer to just give that an ID (if it doesn’t already have one for another purpose) and attach my Javascript later. That’s what over a decade of experience has shown me to be the best approach.

The way to improve on that is to have only the one event handler at a common parent element, such as on the table element itself. That way the table contents can change any way you like, and events bubble up to the table event handler. From there the script can figure out which element was clicked, and then carry on to process things from there.

Hello Paul,

that wasn’t really the question: how event-handler working, and where to attach them.

The question was: Inline or not? And when x || y, why?? - please have a deeper look into the tread.

Regards,

Wolf

Placing event handlers in the JavaScript rather than in the HTML means that your pages will load quicker for those visitors with JavaScript disabled since they don’t need to download a non-working event handler.

It also makes the pages load quicker when you are using the same JavaScript in multiple web pages because then the event handler appears once in the common JS file and not separately in each and every HTML file.

For even greater flexibility you should use event listeners instead of event handlers so that if you add another script to the page that needs to add event processing for the same event on the same tag that the two scripts can do so completely independently of one another. Of course the code to do that is more complex as you need to substitute attachEvent for Internet Explorer.

a = x || y means set ‘a’ equal to ‘x’ provided that ‘x’ exists and is not false, zero, or an empty string OR if ‘x’ evaluates to false then set ‘a’ equal to ‘y’. The || is the OR comparison but with JavaScript even though ‘x’ needs to be evaluated as true or false in determining whether to evaluate ‘y’, it is the original value of ‘x’ that gets copied if it evaluates as true.

So basically a = x || y is the shortest way of saying if (x) a = x; else a = y; or a = (x) ? x : y; - all three of those do the same thing just they use different amounts of code and the || version is the only one that doesn’t need to repeat any of the variable names.

Hi,
Thanx. I found what you said here helpful. (I think you missed your closing head tag). :cool: