I am currently trying to make an image replace another in a fixed position while also changing the color style of the text at the same time. The image and the text needs to change when one or the other is being hovered over by the user. I have the image and text in a div and attempted to use an eventlistener to change the objects.
HTML:
<div id="dequestimg"> <p style="font-size: 75%; float: left; font-weight: bold">Delete Requests:</p> <img src="dequestbutton.png"/> </div>
JavaScript:
document.addeventlistener("mouseover", mouseover); document.addeventlistener("mouseout", mouseout); function mouseover() { document.getelementbyid("dequestimg").style.color = "red"; document.getelementbyid("dequestimg").getelementsbytagname("img") = "dequestbuttonhover.png"; } function mouseout() {kossa document.getelementbyid("dequestimg").style.color = "black"; document.getelementbyid("dequestimg").getelementsbytagname("img") = "dequestbutton.png"; }
I am new to JavaScript so any help would be appreciated.
Advertisement
Answer
Many points here
- You have an unexpected string in your JavaScript making it invalid:
kossa
- JavaScript is case-sensitive, you have to use the correct casing in the function names:
getElementById
,getElementsByTagName
- You can define a variable at the top to select your
div
- You should probably give the
img
element an id as well so you can select it separately - You need to set the
src
property of the image once it’s selected, you can’t just assign it as a string
Here’s a working example
HTML index.html
<!DOCTYPE html> <html> <body> <div id="dequestimg"> <p style="font-size: 75%; float: left; font-weight: bold"> Delete Requests: </p> <img id="image" src="dequestbutton.png" /> </div> <script src="index.js"></script> </body> </html>
JavaScript index.js
const div = document.getElementById("dequestimg"); const img = document.getElementById("image"); document.addEventListener("mouseover", mouseover); document.addEventListener("mouseout", mouseout); function mouseover() { div.style.color = "red"; img.src = "dequestbuttonhover.png"; } function mouseout() { div.style.color = "black"; img.src = "dequestbutton.png"; }