Skip to main content

Browser Default Actions

Browser Events: Browser Default Actions


What is a default action considered in the browser?

View Answer:
Interview Response: There are several different default actions in the browser. For instance, a click on a link initiates the navigation to the specified URL. Another default action is highlighting text when pressing a mouse button as we glide over the text. As developers, we have control over many of these actions.

Is there a built-in function or method to prevent browser actions?

View Answer:
Interview Response: Yes, we can use the preventDefault method to prevent specific browser actions.

Code Example:

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

What happens when you return a false value from a handler?

View Answer:
Interview Response: The value returned by an event handler usually gets ignored. The only exception is returning false from a handler assigned on‹event‹. In all other circumstances, the return value gets disregarded, making no sense to return true.

What is the function of the defaultPrevented property?

View Answer:
Interview Response: The defaultPrevented read-only property of the Event interface returns a Boolean indicating whether the call to Event.preventDefault() canceled the event. The property event.defaultPrevented is true if the default action was prevented and false otherwise.

Code Example:

<p>Right-click for the document menu</p>
<button id="elem">Right-click for the button menu</button>

<script>
elem.oncontextmenu = function (event) {
event.preventDefault();
alert('Button context menu');
};

document.oncontextmenu = function (event) {
if (event.defaultPrevented) return;

event.preventDefault();
alert('Document context menu');
};
</script>