Explaination of onfocus="this.value='';

I found this script, explaination of onfocus="this.value=‘’;, but can’t find the explanation for why it works the way it does. Specifically, where does this.value come from? Can someone supply a reference?

The onfocus event is apart of a family that inherits javascript as part of the HTML attribute, more attributes are…

  • onclick
  • onblur
  • onmouseover
  • onmouseout
  • onmouseenter
  • mouseoutleave

A simple answer to why you can even use this is because all of those attributes above are actually javascript events, when a page loads those attributes are read as HTML but they get rendered as javascript behind the scenes.

When you use one of these events and interact with the element its attached to the object this becomes part of the attribute scope allowing for inline DOM manipulation. So essentially any method you use within script file can be used inline but its not recommended to have large chunks of inline javascript but small inline codes that for instance changes a background color or a value as your example code shows.

Hope that helps bud but if not im sure Paul knows a bit more then me :slight_smile:

It’s a team effort.

When an event is attached to an element using an inline event attribute, the this keyword does not get bound to the element. It instead defaults to the the window itself.

<a id="emeraldCityDirections" href="#yellowBrickRoad" onclick="whereToGo()">But, how do I start for Emerald City?</a>
function whereToGo() {
    alert(this.href); // undefined

The above onclick event will fire, but it won’t be capable of working with the link.

Other problems exist too with inline events, they clutter up your HTML making it harder to understand, they are often repeated over and over again when you are performing the same behaviour on similar elements, it’s not possible for the web browser to cache the script code as it does with external files, and it completely messes up any kind of separation between content and behaviour.

Content, Presentation and Behaviour are HTML, CSS and JavaScript. Keep 'em separate and the on-going maintenance and stability of your code becomes a whole lot easier.

<body><a id="emeraldCityDirections" href="#yellowBrickRoad">But, how do I start for Emerald City?</a>
<script src="script.js"></script>


function whereToGo() {
var link = document.getElementById('emeraldCityDirections');
link.onclick = whereToGo;