Trouble with changing background image on hover

Is there a way to change the background image when hovering over a normal image without altering the original background image?

I attempted to achieve this using z-index values, but unfortunately it did not work as expected. You can view my attempt on this fiddle. It is important that the new image preloads so that users do not experience any delay in loading.

img{
  width: 120px;
  position: relative;
    z-index: -1;
}

img:hover{
     background-image: url('https://i.ibb.co/bsQL6SK/media13-3-blue.png');
      background-position: center;
  background-repeat: no-repeat; 
  background-size: cover;
}
<img src="https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png" alt="">

Answer №2

If you're seeking a purely css-based solution, one approach is to wrap your image in a div and set the background image on the before/after element. Here's a sample code snippet demonstrating this technique. I included a background color for clarity on how it works. Keep in mind that the effectiveness of this solution may vary depending on your specific requirements.

.container {
  width: 120px;
  position: relative;
  display: inline-block;
}

.container:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: none;
  background-image: url('https://cdn.motor1.com/images/mgl/Rzxom/s3/lamborghini-sian-lead.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  z-index: 1;
}

.container:hover:after {
  display: block;
}

.container img {
  width: 100%;
  height: 100%;
}
<div class="container">
  <img src="https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png" alt="">
</div>

EDIT
https://i.sstatic.net/LvXzO.png

Upon closer inspection, you'll notice that the fox news logo appears smaller compared to your larger image. The addition of the green background helps highlight this disparity. To resolve this discrepancy, adjust the sizing so the logo fills the allocated space. Does this explanation make sense?

Answer №3

Website Design

<img src="https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png" onmouseover="this.src='https://i.ibb.co/bsQL6SK/media13-3-blue.png'" onmouseout="this.src='https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png'" alt="">

CSS Styling

img{
  width: 120px;
}

Live Demo Example

If you encounter any further problems, please let me know.

Answer №4

To achieve this effect, you can utilize the onmouseover and onmouseout events.

img{
  width: 120px;
  position: relative;
}
<img src='https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png' onmouseover="this.src='https://i.ibb.co/bsQL6SK/media13-3-blue.png';" onmouseout="this.src='https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png';" />

Answer №5

To achieve the desired effect, you can utilize two image tags and implement a hover toggle function. This way, one image is displayed by default while the other appears only on hover. Here's an example code snippet:

const container = document.querySelector("#image-container");
const imgDefault = document.querySelector("#image-container .default");
const imgHover = document.querySelector("#image-container .hover");

container.addEventListener("mouseover", function(){
  imgDefault.style.display = "none";
  imgHover.style.display = "inline-block";
})

container.addEventListener("mouseout", function(){
  imgDefault.style.display = "inline-block";
  imgHover.style.display = "none";
})
img{
  width: 120px;
  position: relative;
}

.hover {
  display: none;
}
<div id="image-container">
  <img src="https://www.example.com/image-default.png" class="default" alt="">
  <img src="https://www.example.com/image-hover.png" class="hover">
</div>

Answer №6

Utilize the jQuery hover event to dynamically change the image URL and adjust the z-index to 0 while the user hovers over it.

<html>
<head>
<title>title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<img src="https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png" alt="">
</body>
<style>
img{
  width: 120px;
  position: relative;
    z-index: 0;
}

img:hover{
     background-image: img[back];
      background-position: center;
  background-repeat: no-repeat; 
  background-size: cover;
}
</style>
<script>
$('img').hover(function (e) {
if(e.type == 'mouseenter'){
$(this).attr('src', 'https://i.ibb.co/bsQL6SK/media13-3-blue.png');
    }else{
        $(this).attr('src', 'https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png');
    }
});
</script>
</html>

Answer №7

I am a bit unclear on what you meant by (Please refrain from suggesting that I use a normal background image), please excuse me if I misunderstood and unintentionally did the opposite of what you were requesting.

As a beginner, I can think of two approaches using just plain CSS without JavaScript:

  1. Utilizing both images as background images in CSS and toggling their visibility accordingly, although this may not align with your preferences.
  2. Embedding both images in HTML using the img tag, where you can wrap them within an anchor tag or even a div container.

Ensure that both images have the same dimensions.

img{
  width: 200px;
}

a img:last-child {
  width: 200px;
  display: none;  
}
a:hover img:last-child {
  width: 200px;
  display: block;  
}
a:hover img:first-child {
  width: 200px;
  display: none;  
}
<a>
  <img  src="https://cdn.freebiesupply.com/logos/large/2x/fox-news-logo-png-transparent.png" alt="">
  <img  src="https://i.ibb.co/bsQL6SK/media13-3-blue.png" alt="">
</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

Using the EJS if-else statement to iterate through an array of items

I am working on rendering API data using Express (REST) and EJS (template engine) based on the value of the "status" field. If any item in the array has a status other than "CLOSED," it should be displayed, but if all items have the status set to "CLOSED," ...

Steps to capture cell click events in a Kendo grid

My grid is displaying information about students. I want to show a popup when the user clicks on the "StudentId" or "SubjectId" cell in those columns. How can I get the cell click event and verify that it is the right column? @(Html.kendo().Grid<St ...

What is the optimal number of keywords to include in the META keywords tag?

I recently came across a discussion about the importance of the keywords meta tag in HTML for search engine visibility, particularly on platforms like Yahoo! and Ask. While most of us may not have inside knowledge of search engine algorithms, I am curious ...

what is the best method to schedule tasks at a specific time in node-schedule?

I am facing an issue with running a node task daily at 8AM using the node-schedule package https://www.npmjs.com/package/node-schedule. Instead of running every day at 8AM, it is currently running every minute. What method should I use to correctly configu ...

What is the significance of the .jpg?t= in the URL?

This webcam image displays the code ?t=1512496926. What exactly does this code signify? Could it be related to time? Is it just a random string of characters? https://i.stack.imgur.com/ZAZMy.jpg ...

Refresh the page on the same tab after making an AJAX request

HTML: <table border="1"> <tr id="main_account"> <td width="50%"> <h3 style="margin-left:10px">Details</h3> <table width="270"> <tr> <td& ...

Issue with Highcharts: The useHTML flag is not functioning properly when trying to render labels

Currently, I am utilizing highcharts and a phantomjs server for rendering charts and labels. However, I have encountered an issue where the useHTML flag does not function as expected when rendering the labels. Following the instructions in the documentatio ...

Combining 2 objects with changing properties using jQuery

Two javascript objects need to be merged, but one contains dynamic form field values saved as variables. An example code snippet can be found here: http://jsfiddle.net/ZAa7L/ I came across this code in a stackoverflow post where it worked perfectly. Now ...

Error: Attempted to bootstrap Angular multiple times

While developing an app using angularjs, everything functions correctly after loading a web page. However, a message appears on the console saying: WARNING: Tried to load angular more than once. Upon checking the angular.js file, I found this code snippe ...

Is there a method available for troubleshooting unsuccessful AJAX requests? Why might my request be failing?

Whenever I click on a button with the class "member-update-button," an alert pops up saying "got an error, bro." The error callback function is being triggered. Any thoughts on why this might be happening? No errors are showing up in the console. How can I ...

The function chrome.cookies.get is returning undefined or causing an error to be thrown

chrome.cookies.get({url:"http://www.dahotre.com", name:"userid"}, function(){}) returns undefined when checked in the console. If I exclude the optional empty function(), it raises an error. chrome.cookies.get({url:"http://www.dahotre.com", name:"userid"} ...

The process of adding information to a table through ajax is not functioning properly

Below is a representation of the table I have: <table class="table" id="tbl"> <thead> <tr> <th>ID</th> /* some headings */ </tr> </thead> <tbody class="tbodyA ...

I would like to verify the individual listed in the table to confirm their attendance

I am trying to build an entry panel with a text box using ajax and PHP. It needs to validate the entered ID in one table, and if the ID is valid, insert the ID, date, time, and status into another table. select id="$id" from table1 if the id is valid inse ...

Exploring the various approaches for accessing nodes in JavaScript and jQuery

I'm a bit perplexed by the behavior of selectors in my Javascript/jQuery code. I have two methods that are being called in nearly the same way, yet they are returning different selectors and I can't figure out why. if (document.URL.indexOf("sear ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...

Submitting a specific form when a change occurs in CodeIgniter

I am currently developing a POS web application. My current task involves creating a form for each item in the cart/order, meaning multiple forms generated in a loop with unique IDs (e.g. 'id'=>'cart_'.$line )(cart_1, cart_2). I hav ...

How can I stop an element from shifting when hovering over a border?

My HTML structure is set up like this: ul { list-style: none; padding: 0; margin: 0; } li:hover { border: 2px solid; } <ul> <li>one</li> <li>two</li> <li>three</li> </ul> When the `:hover` e ...

Issues have been reported with the SVG filter URL functionality in Angular 4

Hey there! I'm currently working on drawing a line using SVG in Angular and incorporating some filters for glow effects. However, I've run into an issue where the filter URL is not functioning properly in the browser - nothing is being displayed ...

Restart jQuery animation upon modal closure

I'm facing an issue with an animation where a bottle gets filled up to a specific point from data stored in the database. The problem arises when I open and close a modal, as the animation continues running even after the modal is closed. My goal is t ...

What is the method to retrieve the base host in AngularJS?

I need assistance with the following URL: https://192.168.0.10/users/#!/user-profile/20 When I use $location.host, it returns 192.168.0.10 However, I only want to extract https://192.168.0.10 What is the best way to achieve this? ...