How to Change Image on Hover Using CSS or JQuery

Last Updated on August 26, 2022 by Roshan Parihar

In this tutorial, learn how to change image on hover using HTML, CSS and jQuery. The short answer is to use the background property of CSS with :hover selector.

If you want to use only jQuery for this, you can also use the jQuery attr() function with the hover() function for hover event.

Let’s find out the different examples given below.

Method 1: How to Change Image on Hover Using CSS Only

To change the image on hover using only CSS, you have to <div> element and add an image to it using background property. After that, use the :hover selector inside which you have to specify another image to replace with the previous image on div hover.

Output

Hover over the above image to see the changed image

The above example contains the image element. When you hover over the above image, you will get the changed image. This simple method requires only CSS and HTML to change the image on hover.

Method 2: Change Image on Hover Using JQuery Only

If you want to change the image on hover using only jQuery, you have to first add an image using the <img> element of HTML. After that, you have to use the hover() function that takes two arguments for the hover events on an image.

The first argument is to specify the new image to replace with the current image using attr() to change the source of the image. The second argument is to specify the current image to return on mouseout using the attr() function.

Output



Hover over the above image to see the changed image

Now, hover over the above image to see the newly changed image using jQuery. It works the same as the previous example output. However, the method is different as the previous example uses only CSS.

Replace Img on li Mouseover Using CSS and JQuery

In addition to the above example, you can also replace images on li mouseover using CSS and jQuery. The below example shows the list of boxes using the list elements to hover and change the image. The example uses the mouseover() function with show() function and hide() function of jQuery.

Initially, the images are in a hidden state and when you hover over the button, you will get the related images.

Output

Hover over the below list buttons to display image.

  • Show Manager
  • Show HR
  • Show Developer
  • Show Designer
Manager How to Change Image on Hover Using CSS or JQueryManager
HR How to Change Image on Hover Using CSS or JQueryHR
Developer How to Change Image on Hover Using CSS or JQueryDeveloper
Designer How to Change Image on Hover Using CSS or JQueryDesigner

The above example is the live example to hover over the designation of employees in a company listed above. You can hover over the list buttons given above to get the person’s image with the designation. The image changes accordingly with the mouse hover event using the mouseover() event of jQuery.

You May Also Like to Read