JavaScript: Event handlers and more about links

HTML links can reference URLs with different protocols, such as http:, ftp: or news:. For JavaScript there is an extra protocol: javascript:. The following example will create a link that opens a warning window with the text "This is a cool Text" when you click it.

Take care of the quotation marks. The quotation marks of the href-attribute mustn't be the same as the ones of the JavaScript rule, otherwise, the code is interpreted incorrectly. Thus you can use either Single quotes outside (in this case, href) and double quotes for JavaScript or do it the other way around. It is not important in JavaScript whether you use single or double quotes. It only matters that they end the same way they start.

Right

Wrong


document.write("A sentence.');
document.write('A sentence.");


Although this javascript: pseudo-protocol is simple to use, it has a disadvantage: Older browsers that do not support JavaScript will show an error message. In the following section you will see a better solution.

Event handlers

When performing certain actions, such as clicking on a link, JavaScript-internally a so-called event is entered. Some of these events can be caught with JavaScript and respond to. This requires the event handlers which can occur as attributes of some HTML elements. We first show the most important.

By default, the following applies: An event handler always starts with on. The event handler that is responsible for the clicking of links is called onclick. If this link is clicked, a modal window opens.


Quotation marks

Also be careful with the usage of quotation marks here!


In principle, it is super - browsers that support JavaScript run the code, but then follow the link. Browser without JavaScript support only "see" the link and try to access the target.

Normally this is not desired. The href attribute must be set, otherwise the link will not appear (this applies no longer to HTML5. look here for more information ). But there is a way to specify a link wich does not load a page:

Click me

Continue to part 4



Comment