Back to Home

Browser default actions

Many events automatically lead to certain actions performed by the browser. For instance: - A click on a link - initiates navigation to its URL. - A click on a form submit button - initiates its submission to the server. - Pressing a mouse button over a text and moving it - selects the text. If we handle an event in JavaScript, we may not want the corresponding browser action to happen, and want to implement another behavior instead.

Preventing browser actions

There are two ways to tell the browser we don’t want it to act: - The main way is to use the event object. There’s a method event.preventDefault(). - If the handler is assigned using on (not by addEventListener), then returning false also works the same. In this HTML, a click on a link doesn’t lead to navigation; the browser doesn’t do anything: In the next example we’ll use this technique to create a JavaScript-powered menu.

Example: the menu

Consider a site menu, like this: Here’s how it looks with some CSS: [iframe height=70 src=“menu” link edit] Menu items are implemented as HTML-links , not buttons

<a href="/" onclick="return false">Click here</a>
or
<a href="/" onclick="event.preventDefault()">here</a>
Example:

Follow the lesson from Microsoft Web-Dev-For-Beginners course

Tags: web,development