Everything you need to know about JavaScript
entities
Let's officially explain just what JavaScript entities are,
and what they can do. A JavaScript entity is a special piece of JavaScript
code that can be inserted directly as the value of any HTML
attribute inside your HTML document. Since it's a JavaScript code, the value
does not have to be static, and can change on the fly according to it's
manipulating script. The syntax for a JavaScript entity looks like this:
&{JavaScript-statements };
Ok, this isn't exactly helping, so let's put everything into
context. The below shows two HTML tags- the first one uses a regular HTML
value for it's attribute; the second, a JavaScript entity:
Regular HTML value:
<body background="image1.gif">
JavaScript entity value:
<body background="&{JavaScript-statements };">
What's so special about the second example? Everything!
By using JavaScript entities, HTML attribute values no longer are static,
but dynamic, changing values that can be manipulated using JavaScript.
In general, any JavaScript statement can be embedded inside
the entity. If the statement is simply a JavaScript variable, the value of
this variable is used as the value of the HTML attribute. Otherwise, the
value of the last statement or expression within the entity is adopted as
the attribute's value. Here's a simple example that uses JavaScript entities
to assign a different image path to a particular <img>, depending on the
time of the day:
<script>
var myimage="day.gif"
var today=new Date()
var day_night=current.getHours()
//if the hour is pass 12 p.m
if (day_night>12)
myimage="night.gif"
</script>
<img src="&{myimage };">
I created a script that determines the hour of the day, and
depending on that, assign variable "myimage" a different image path. Here's
where things get interesting though. Notice how "myimage" is used directly
inside the <img> tag, as it's src attribute's value. That's the essence of
JavaScript entities- it allows you to use JavaScript as the value of
otherwise static HTML attributes. The above image will be different,
depending on whether it's day or night.
Before moving on to more examples on using JavaScript
entities, let's first look at the all important question of how widely this
cool feature is supported.
|