I have a challenge where I need 10 unique links that behave in a specific way when the user hovers over them. Essentially, I want the background image of the containing div to change and for a tooltip text to fade-in on top of each link.
I've attempted to achieve this functionality using JavaScript, but it's resulted in lengthy and repetitive code. I'm looking for a more efficient solution that avoids unnecessary repetition.
// JS functions for mouseover and mouseout behavior
document.getElementById("d1").onmouseover = function() {
mouseOver(1);
};
document.getElementById("d2").onmouseover = function() {
mouseOver(2);
};
document.getElementById("d3").onmouseover = function() {
mouseOver(3);
};
document.getElementById("d1").onmouseout = function() {
mouseOut(1);
};
document.getElementById("d2").onmouseout = function() {
mouseOut(2);
};
document.getElementById("d3").onmouseout = function() {
mouseOut(3);
};
function mouseOver(num) { // Function to handle hover behaviors based on link number
document.getElementById("dogs").style.background = getColor(num); // Get color based on link number
document.getElementById("tooltiptext" + num).style.visibility = "visible";
}
function mouseOut(num) { // Function to handle mouseout behaviors based on link number
document.getElementById("dogs").style.background = "black";
document.getElementById("tooltiptext" + num).style.visibility = "hidden";
}
#dogs {
float: right;
margin-top: 5%;
background: black;
width: 150px;
height: 150px;
}
#d-list {
color: white;
direction: ltr;
float: right;
width: 60%;
height: 60%;
}
#tooltiptext1,
#tooltiptext2,
#tooltiptext3 {
color: black;
background-color: gray;
width: 120px;
height: 30px;
border-radius: 6px;
text-align: center;
padding-top: 5px;
visibility: hidden;
}
<div id="animals">
<div id="dogs"></div>
<div id="d-list">
<pre style="font-size:22px; color:darkorange">dogs</pre><br />
<pre><a href="#burger" id="d1">white Husky</a></pre>
<p id="tooltiptext1">Tooltip text1</p>
<pre><a href="#burger" id="d2">black Bull</a></pre>
<p id="tooltiptext2">Tooltip text2</p>
<pre><a href="#burger" id="d3">brown Rex</a></pre>
<p id="tooltiptext3">Tooltip text3</p>
</div>
</div>
Please consider that all links will update the same outer container div, with the intention of changing its background image and displaying tooltips above the links. So, do you have any suggestions for achieving this efficiently?