I’m building a site for a retailer. I’m working on their store locations page, which has 4 different street locations. Each street address is wrapped in its own paragraph tag. All four paragraphs are inside a div container which has an ID named “box_1”.
I’ve written an event handler that changes the background color of the first paragraph element. However, I don’t want to write the same redundant code for the other 3 paragraphs, if I don’t have to.
I want JS to first determine which paragraph is being hovered over and take its position in the array and load it into the brackets in the event handler. Example: hover mouse over paragraph 2 and load “1” into element[1].onmouseover = function() {// my code};
Below is the code I have so far:
<div id="box_1">
<p>18901 Kansas Avenue, Jimmytown, NE </p>
<p>5015 Cornman Lane, Crybaby, MN </p>
<p>847 Halfstack Avenue, Crumble, GA </p>
</div>
// javaScript:
var divPoint = document.getElementById("box_1"); // ID for the div
var mousePoint = divPoint.getElementsByTagName("p"); // p elements inside div
// mouseover event handler
mousePoint[0].onmouseover = function() {
mousePoint[0].style.backgroundColor = "#a80";
};
First, attach the event to the div
. In onmouseover
function, you can have a variable name event
. Then, call event.target
to get the element triggering the event.
You may want to implement onmouseout
also to clear the background. Here is the code.
var divPoint = document.getElementById("box_1");
divPoint.onmouseover = function(event) {
var element = event.target;
if (element.tagName.toLowerCase() === 'p') {
element.style.backgroundColor = "#a80";
}
};
divPoint.onmouseout = function(event) {
var element = event.target;
if (element.tagName.toLowerCase() === 'p') {
element.style.backgroundColor = "#fff";
}
};
You can test it on JsFiddle.
For more information about event.target
, please take a look at W3Schools.