Current course:

Javascript escape character

When writing javascript, it's sometimes necessary to use what's called an "escape character".

Every HTML attributes value must be enclosed in matching quotation marks. So, if you start with a double quote, you must end with a double quote.

Like this: <a href="test.php">Test</a> or <a href='test.php'>Test</a>

But what if we want to use javascript to change it's background image?

Look at the example below:

<a href="index.php" onmouseover="document.getElementById(this).style.backgroundImage = 'url('myImage.jpg')';" />

The onmouseovers value starts with a double quote, then continues through the code until it finds the next double quote, marking the end of its value. So, we cannot use any double quotes in our javascript. We instead use single quotes. BUT, because we're using just single quotes, our javascript now reads like this:

document.getElementById(this).style.backgroundImage = 'url('myImage.jpg')';

Notice anything wrong?

The Javascript line above will cause an error because it thinks the string is "url", then a Javascript variable "myImage.jpg", then another string ")" because it starts with a single quote, and continues until it finds the next single quote, and thinks of that as the end of our string.

To combat this, we can use an escape character, which in the case of Javascript is a backslash \

document.getElementById(this).style.backgroundImage = 'url(\'myImage.jpg\')';

The \ tells Javascript that the character following it should be written just as part of a string, and not interpreted as the start or end of a quotation.

So, the correct code for the link above is:

<a href="index.php" onmouseover="document.getElementById(this).style.backgroundImage = 'url(\'myImage.jpg\')';" />

The HTML attribute starts and ends with a double quotation mark, and the javascript strings starts and ends with a single quote. The single quotes WITHIN the javascript string are not considered an end for it's string.