Jump to content

Somebody should help me


Recommended Posts

Let's set a few things up first. Firstly, in HTML create the image tag with an id and some alt text:

<img id="image" src="image.png" alt="image-text">

Next, in JavaScript let's assign the image tag to a variable. Doing so will make it's alt property accessible for later use in the div tag:

// assign the img tag by id to the "img" variable
let img = document.getElementById("image");


Now let's create an empty div in HTML, with an id of "alt-text". You can do this entirely in JS, but let's use HTML for this example. Add it just below your img tag from the first step:

<div id="alt-text"></div>

Next, in JavaScript let's create a variable to reference the empty div and a function to set the text and background colour of the div:

imgFunc = () => {
	// assign the empty div to a variable
	let altDiv = document.getElemenetById("alt-text");

	// set the text of the div to the alt property from the img variable created earlier
	altDiv.innerHtml = img.alt;

	// set the background colour of the div
	altDiv.style.backgroundColor = "blue";

Now, there are better ways to set the text, but innerHtml is a quick way to demonstrate. Explore the options available to you on the W3Schools website.
I've gone with blue here as the background colour, but you can choose whatever colour you want.

Finally, let's add a mouseover event to the img tag from the first step, and use it to call our function:

<img id="image" src="image.png" alt="image-text" onmouseover="imgFunc()">

And that's it.

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...