Include a hyperlink that is activated when hovering over an image

UPDATE: I am amazed by the quick responses, this is my first time using this platform. Thank you to everyone who helped out. The person who provided the answer understood exactly what I was looking for. To others who responded, thank you as well.

I need help adding a link to an image that changes when hovered over. I want the image to switch to another image with a link attached. Can anyone assist me?

HTML

<img src="don.png" class="artist" onmouseover="hover(this);" onmouseout="unhover(this);" a href="https://privatelink.com"/>

JS

function hover(element) {
  element.setAttribute('src', 'ht.png');
}

function unhover(element) {
  element.setAttribute('src', 'don.png');
}

Answer №1

Initially, there is an error in your HTML syntax. The a and href do not belong as attributes of an img element tag. Refer to this link for a list of available attributes. If you want to include custom data with an image, consider using the data-* attribute. See more details here. This can then be utilized in JavaScript if necessary.

Among the numerous solutions provided at this question about adding a link to an image dynamically, one method involves:

var parentEl = document.getElementById("myimg").parentElement;
var imgEl = parentEl.innerHtml;
parentEl.innerHtml = '<a href="test.html">' + imgEl + '</a>';

Alternatively, jQuery's .wrap() function can also be used, as mentioned in the aforementioned discussion.

To see an example specific to your scenario, check out this JSFiddle demo.

Answer №2

one way to achieve this is by following these steps

HTML

<img src="don.png" class="artist" id="myImage" onmouseover="hover("myImage")" onmouseout="unhover("myImage")" a href="https://privatelink.com"/>
  

JS

 function hover(element) {
       document.getElementById(element).src='ht.png'
    }
  
   function unhover(element) {
       document.getElementById(element).src='don.png'
    }
  

Answer №3

$(document).ready(function() {
$("#myimage").hover(function() {
   var src = "https://privatelink.com";
   var a = $("<a/>").attr("href", src);
    $( this ).wrap(a);
 });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   
<figure id="myimage">
  <img src="pic_trulli.jpg" alt="Trulli" style="width:100%">
  <figcaption> Fig.1 - Trulli, Puglia, Italy. </figcaption>
</figure>

Answer №4

const selectedImage = document.querySelector("#image_link");
selectedImage.addEventListener("mouseover", (event) => changeImage(event, "over"));
selectedImage.addEventListener("mouseout", (event) => changeImage(event, "out"));
function changeImage(event, action) {
  if (action === "over") {
    selectedImage.setAttribute("href", "newurl1.html");
    // update image
    selectedImage
      .querySelector("img")
      .setAttribute(
        "src",
        "https://images.unsplash.com/photo-1542353436-312f0e1f67ff?auto=format&fit=crop&w=400&q=80"
      );
  } else {
    selectedImage.setAttribute("href", "newurl2.html");
    // update image
    selectedImage
      .querySelector("img")
      .setAttribute(
        "src",
        "https://images.unsplash.com/photo-1558981852-426c6c22a060?fit=crop&w=500&q=80"
      );
  }
}
<a href="#" id="image_link">
        <img src="https://images.unsplash.com/photo-1558981852-426c6c22a060?fit=crop&w=500&q=80" class="artist"/>
    </a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting the user's language in PhoneGap can be done in a variety of ways

I attempted to retrieve the language value of the device using the globalization plugin. I followed all installation procedures, read through the documentation, and searched for answers on this platform, but unfortunately, none of them provided the solutio ...

Customizing a responsive background image within a div using Bootstrap 3

Is there a way to style the background image of my header div like the one featured on Mr. Bill Gates' website at ? I noticed that the height of Mr. Bill Gates' header background image remains consistent, even on smaller screens. I've atte ...

Issue: The npm module 'moment' cannot be located

My Meteor app works flawlessly on localhost, but when deployed to a remote heroku server, I encounter these errors. (I am following this) Any suggestions on how to resolve this issue? 2016-09-09T13:26:02.533532+00:00 heroku[web.1]: Starting process with ...

Transform Image on Hover in ReactJS

I am working on a Card Component that includes an image and text. Initially, the image is redImage and the text is black. When hovering over the card, I want the redimage to change to whiteimage and the text color to change to white as well. The content ...

What's causing the unexpected rendering outcome in Three.js?

Here is a mesh created in Blender: https://i.sstatic.net/KBGM5.jpg Upon loading it into Three.js, I am seeing this result: https://i.sstatic.net/PCNQ8.jpg I have exported it to .obj format and ensured all faces are triangulated. I am not sure why this is ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...

Exploring the JsonArray Response entity

Trying to decode my fetch response: fetch('restservices/users/', fetchOptions) .then(function (response) { if (response.ok) { console.log('1'); console.log(response) const responseSjon = response.json ...

"Utilizing Javascript in an ERB view file within the Rails framework

In my .js.erb file, I need to execute a conditional statement when an ajax call is triggered. Below is the code snippet: function updateContent() { $('.organiser__holder').html('<%= escape_javascript render("filter_links") %>' ...

What is the process for attaching an analytics tag to data messages using the Firebase Admin SDK with Javascript or TypeScript?

Adding a label to my message is something I'm trying to do. I checked out the official guidelines here and found a similar question answered on Stack Overflow here. I've been attempting to implement this in JavaScript, but I'm stuck. Here& ...

What are the steps to use the vue-text-highlight feature?

I am attempting to implement an example from the basic usage section of https://github.com/AlbertLucianto/vue-text-highlight. However, upon opening index.html in Firefox, I am only greeted with a blank page. You can find the code I am using at https://git ...

How can I make an image fill the container with CSS zoom effect

My website features a full viewport image as the background beneath the Nav Bar. I am looking to achieve a specific effect on mobile where the image is zoomed in and centered without distortion, allowing some of it to still be visible as a background. The ...

The hidden overflow seems to be inconsistently effective

I've been working on creating some buttons with a rollover state. I have an image inside a div with overflow:hidden to hide the inactive state, but sometimes it doesn't work properly. What's even stranger is that when I inspect the page usi ...

Implementing a keypress function that can handle duplicate names

HTML <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="total" type="text" value="0" disabled="disabled"/> Javascript $('[name="pm"]' ...

select2 with customizable multi-column layout

Looking to create a multi-column select2 with a dynamic number of columns by specifying the number of columns as a data attribute in the select tag, or utilizing another method. <select data-cols="2,6,4"> <!--note data-cols--> < ...

Browsing with PHP/HTML on Safari from Mac Os 10.6.5 seems to run at a sluggish pace

This is the program: <?php require_once 'swift-mailer/lib/swift_required.php'; $name = $_POST['name']; $email = $_POST['email']; $form_subject = $_POST['form_subject']; $form_message = $_POST['form_message ...

Developing dynamic HTML content using Android and JavaScript to insert JavaScript code into the head tag dynamically

I need to incorporate a banner into my Android application in a specific way. Upon receiving the following Javascript code from the server: <script type="text/javascript" src="http://rm.face.ua/adriver.core.2.js"></script> <div id="adri ...

What are the steps to achieve such a design?

Can you show me how to create a single layout using HTML and CSS? I am struggling with splitting the screen properly. Could you provide a simple example, maybe on jsfiddle? https://i.stack.imgur.com/d2rbn.jpg Thank you in advance! EDIT: I have added a ...

AngularJS synchronous $resource functionality allows for the ability to make parallel API

I'm facing a dilemma because I understand that Javascript isn't designed for synchronous work, especially in the case of AngularJS. However, I find myself in a situation where I require it. The main page on the "www" domain (built with AngularJS ...

choose and adjust elements within a three-dimensional scene using three.js

I have a JSON file containing object data that I load into my scene using ObjectLoader. After adding the objects to the scene, I want to customize their textures by adding parameters like THREE.SmoothShading and an envMap. I know how to find a specific obj ...

Why is my column getting devoured even though it has custom content tailored to it?

In my layout, I have one column, one row, and three nested columns. Each column contains a custom-designed button instead of using the default Bootstrap button. However, there seems to be an issue where one of the columns is getting cut off. To better und ...