Replace the background image upon hovering over a div using jQuery

Creating Dynamic Backgrounds on Hover

https://i.sstatic.net/K9wB2.jpg

I am looking to implement a feature where users can hover over each red box in the picture, triggering a change in the background of the entire container (currently grey) to reveal a different image for each box. In my CSS, I have set up the initial background as grey:

#service {
background: grey;}

To achieve this effect, I wrote the following jQuery code:

$service = $('#service');
$('.service-list').on('mouseover', 'div', function() {
    $service.css('background-image', 'url(' + $(this).attr("data-uri") + ')');
});

However, this implementation does not seem to be working as intended. Furthermore, I would like to preload these background images, which are quite large (around 650kb), to ensure a smooth and instantaneous transition. One approach I was considering is creating a hidden div for preloading:

<img src="path/image-01.png" width="1" height="1" alt="Image 01" />

I am unsure if this method will be effective. Any assistance or guidance on how to achieve this functionality would be greatly appreciated.

edit---- Just to clarify, my goal is to change the background of the services container upon hovering over the red boxes, not modify the background of each individual box.

Answer №1

To achieve this effect, you can utilize the jQuery hover function.

$service = $('#service');

$('.greay-box').hover(function() {
    $service.css('background-image', 'url(' + $(this).attr("data-uri") + ')');
        }, function(){

    $service.css('background-image', '');

    });

Check out this example on JSFiddle. I hope this explanation proves helpful to you.

Answer №2

Hello, hopefully you are interested in trying something like this by manipulating the image with Jquery.

var changeImage = function () {
        var $this = $(this);
        var newSource = $this.data('alt-src');
        $this.data('alt-src', $this.attr('src'));
        $this.attr('src', newSource);
    }

    $(function () {
        $('img.xyz').hover(changeImage, changeImage);
    });
    .my {
        width:100px;
        height:100px;    
        overflow:hidden;
         border: 2px solid red;
          float:left; 
          padding:2px;
          margin:2px;
        
    }
    .my img {
        min-width:100%;
        max-width:100%;
    }
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>


<div class="row">

<div class="my">
   <img class="xyz" data-alt-src="https://s-media-cache-ak0.pinimg.com/236x/5d/63/2e/5d632ede715b92de1c2db866029282b5.jpg" src="http://wall-papers.info/images/grey-background-wallpaper/grey-background-wallpaper-23.jpg" />
</div>
<div class="my">
   <img class="xyz" data-alt-src="https://s-media-cache-ak0.pinimg.com/236x/5d/63/2e/5d632ede715b92de1c2db866029282b5.jpg" src="http://wall-papers.info/images/grey-background-wallpaper/grey-background-wallpaper-23.jpg" />
</div>
<div class="my">
   <img class="xyz" data-alt-src="https://s-media-cache-ak0.pinimg.com/236x/fa/11/c2/fa11c23eddc07d0dd8b26432750df85e.jpg" src="http://wall-papers.info/images/grey-background-wallpaper/grey-background-wallpaper-23.jpg" />
</div>
<div class="my">
   <img class="xyz" data-alt-src="https://s-media-cache-ak0.pinimg.com/236x/fa/11/c2/fa11c23eddc07d0dd8b26432750df85e.jpg" src="http://wall-papers.info/images/grey-background-wallpaper/grey-background-wallpaper-23.jpg" />
</div>
</div>

  </body>
    </html>

You can also view the fiddle demonstration here: UPDATED FIDDLE DEMO LINK

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

Error in TypeScript: The property 'data' is not found within type '{ children?: ReactNode; }'. (ts2339)

Question I am currently working on a project using BlitzJS. While fetching some data, I encountered a Typescript issue that says: Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339) import { BlitzPage } from &q ...

Html Client Side Caching

I am working on an ASP.net/C# application that includes a Header, Footer, Main Menu, and Side panel in the master page. I would like these elements to be loaded only once and then cached on the client side so that they can be retrieved from stored HTML dur ...

Utilizing Ajax XMLhttprequest to Send POST Request to PHP Script and Dynamically Rotate an

I'm facing some challenges with a task I am trying to complete. Specifically, I am attempting to use PHP and Ajax to rotate an image by 90 degrees with each button press. However, I am encountering errors in my PHP script because I am not sending the ...

Choose all elements that share a common class

I want to create a hover effect that highlights all elements on a page with the same class. This is the code I currently have: $(document).ready(function () { $('p.myclass').mouseover(function () { $(this).addClass('hover'); }); $( ...

How can one use jQuery to target elements that have names that are in an array format?

Is there a way to retrieve the values of these elements and send them as an array using ajax? <input type="checkbox" name="Broadcast[m]"/> Members <input type="checkbox" name="Broadcast[i]"/> IATA agencies <input type="checkbox" name="Bro ...

The JQuery mmenu breaks free from its constraints within a Bootstrap 4 design

Whenever I zoom in on my page or view it in responsinator.com, particularly in landscape view, the menu fails to collapse into the mobile version. I have implemented the jquery mmenu plugin alongside bootstrap 4 justified nav. After attempting to remove ...

What method is most effective for transferring arrays from C# to Javascript in a simple and straightforward manner?

Although there may be similar questions here, none of them are asking the exact same thing as mine. For my ASP.NET MVC4 project, I have decided to use aspx as my view engine. Within my views, I have integrated a JavaScript code that takes a table of value ...

Tips for picking out React subcomponents using CSS

Currently, I am creating a SCSS file for my React application that incorporates React Semantic UI (). I am encountering difficulty selecting subcomponents within the CSS. Specifically, how can I target elements like <Item.Group> tag? I attempted usi ...

Get the video file from a web link without the need to launch a Chrome browser

Currently, I am enrolled in a course that consists of around 150 videos. Progress Update: At the moment, there is no option to download these videos directly. To retrieve the URL for each video file, I have developed a script that I execute through the C ...

Is it possible to have a variable number of dynamic CSS Grid columns with the option of including a header or footer

Implementing a dynamic number of columns with CSS Grid is a breeze. .grid { grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); } // These .cells are beautifully aligned <div class="grid"> <div class="cell"></div> ...

What is the best way to add messages in between rows?

I'm working on a code snippet and I need help figuring out how to number all the rows in a table. When clicking on the "Read" button, I want a box to display below the associated row with a message. However, I'm struggling to correctly identify t ...

Support the Cause with Paypal Contributions on Angular/Bootstrap Website!

I'm currently in the process of developing a website using Angular and Bootstrap for a non-profit organization that will facilitate donations through Paypal. On the platform, users will have the option to select their donation frequency (Weekly, Mont ...

Ways to validate the present date and time using Jquery

Is there a method in Jquery to retrieve the current date and time? ...

Display markers on the canvas

I am having trouble painting points from a JSON object on canvas using the following code. Can someone help me identify where I went wrong? var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var t = [{"prevX":39,"prevY":58,"currX ...

Sorting elements to the beginning of each nested array

Looking to rearrange the elements in the given nested array, moving the element with the id 'cat_spc_my_special_id' to the top of the list using the keyword 'special'. There are 4 items currently in the above array, and the goal is to ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

The most effective method for mapping JSON data to a <Table/> component using the Fetch API in React.js

I'm perplexed that I have to ask such an obvious question, yet I keep encountering errors in the console log. I'm attempting to map some JSON elements to a table but can't seem to figure out the correct way. The console is indicating it does ...

Encompassing object with Mobx observables

I am searching for the best approach to implement @observable on a deeply nested JSON object structure, such as a tree. The data tree can go quite deep, with each node having multiple properties. However, I only need to observe one specific property in eac ...

Utilizing the power of Angular's $resource within a factory to showcase information stored in a deeply nested

Just starting to explore the world of $resource concepts and facing a challenge with a piece of code that involves fetching data from a nested JSON. I've created a factory method that successfully retrieves the data and I can see it in the response he ...

Refresh treeview in master page while loading ASP page without refreshing the entire page

Is there a way to load an aspx page without refreshing the treeview on the master page? Currently, I have a master page with a treeview where clicking on a leaf refreshes the entire page instead of just the content placeholder. Can anyone suggest a solutio ...