Shreya is adding links to her school website. She wants that the link colour…
2017
Shreya is adding links to her school website. She wants that the link colour should change as soon as the visitor's mouse pointer is over the link and then the original colour of the link should be restored when the mouse points anywhere else on the page. which of the following two event handlers will be required for the script to achieve this effect ?
Answer: B. onMouseOver and onMouseOut — Concept: In the DOM event model, mouse events belong to two different families. Pointer-position events fire when the pointer crosses an element's boundary —…
- A.
onMouseOver and onMouseUp
- B.
onMouseOver and onMouseOut
- C.
onMouseIn and onMouseOut
- D.
onMouseDown and onMouseUp
Attempted by 407 students.
Show answer & explanation
Correct answer: B
Concept: In the DOM event model, mouse events belong to two different families. Pointer-position events fire when the pointer crosses an element's boundary — one event as the pointer enters the element and a matching one as it leaves — and no button has to be pressed for them to run. Button-state events fire from the physical press and release of a mouse button and say nothing about a boundary being crossed.
Application: The effect described here has two separate moments, so the script needs one handler for each of them.
The pointer moves onto the link. That is a boundary entry, so the entry handler onMouseOver runs, and inside it the link's colour is set to the new colour.
The pointer moves off the link to anywhere else on the page. That is a boundary exit, so the exit handler onMouseOut runs, and inside it the colour is set back to the original value.
The script therefore needs the handler pair onMouseOver and onMouseOut.
Written directly on the anchor tag:
<a href="page.html"
onmouseover="this.style.color='red';"
onmouseout="this.style.color='';">Visit</a>Or assigned from JavaScript:
element.onmouseover = function () { this.style.color = 'red'; };
element.onmouseout = function () { this.style.color = ''; };Cross-check against the other handler names that appear here:
onMouseUp fires when a mouse button that was pressed is released. A visitor who simply moves the pointer away never presses a button, so a restore step wired to it would never run.
onMouseDown fires when a button is pressed while the pointer is over the element. Like onMouseUp it reports button state, not the crossing of the link's boundary.
onMouseIn is not a handler name in the DOM event set at all. The non-bubbling entry and exit handlers are spelled onMouseEnter and onMouseLeave, so a pair built on onMouseIn could never be wired up.
The same visual effect can also be produced without any JavaScript, using the CSS :hover pseudo-class, for example a:hover { color: red; }
Result: the two event handlers required are onMouseOver and onMouseOut.
A video solution is available for this question — log in and enroll to watch it.