elleasan elleasan - 14 days ago 9
Javascript Question

How to create Javascript buttons that change image & each image links to url & active button has highight color

Using the example shown here or code below shows how javascript buttons can be used to toggle between images (on button show bright lightbulb image on and off button shows dark lightbulb image).

But, I also need each image to link to a different url webpage when image (not button) is selected.

The button would control the image changing and each image when clicked would link to different url.

Is there also a way to create a color tint for the active button.

I would like to use this script repeatedly for several groups of buttons and images on the same page. I'm also open to any other scripting ideas.

The sample script below is javascript placed in body of html page:

<button onclick="document.getElementById('myImage').src='http://www.w3schools.com/js/pic_bulbon.gif'">Turn on the light</button>
<img id="myImage" src="http://www.w3schools.com/js/pic_bulbon.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='http://www.w3schools.com/js/pic_bulboff.gif'">Turn off the light</button>

Answer

You can wrap the image in an anchor tag and then update the href attribute similarly to how the src attribute is updated on the img elements.

<button onclick="document.getElementById('myImage').src='http://www.w3schools.com/js/pic_bulboff.gif';document.getElementById('myLink').href='http://www.google.com'">Turn on the light</button>

<a id="myLink" href="http://www.google.com">
<img id="myImage" src="http://www.w3schools.com/js/pic_bulboff.gif" style="width:100px">
</a>
<button onclick="document.getElementById('myImage').src='http://www.w3schools.com/js/pic_bulbon.gif';document.getElementById('myLink').href='http://www.yahoo.com'">Turn off the light</button>

Comments