Switching the background image when hovering over a list element

Looking at the screenshot, it's clear that there is an unordered list with a background image set on the div. What I am trying to achieve is to have the background image change whenever I hover over a list item. Each list item should trigger a different background image upon hovering. How can I accomplish this? All the solutions I've come across only provide guidance for changing to a single image.

Take a look at the screenshot below:

https://i.stack.imgur.com/hv3vp.jpg

I have already hovered over the first list item in the screenshot.

Here is the CSS for the div:

.body {
  display: block;
  float: left;
  background-image: url("bgdef.jpg");
  background-repeat: no-repeat;
  position: static;
  width: 100%;
  height: auto;
  margin: 0;
}

.menu {
  width: 250px;
  padding: 0;
  margin: 100px 0px 33% 75%;
  list-style-type: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
}

.menu a:link,
a:visited,
a:hover,
a:active {
  text-decoration: none;
  bottom: auto;
  padding-bottom: auto;
  text-shadow: none;
}

.menu li {
  background-color: white;
  margin: 10px;
  padding: 3px 0 3px 10%;
  border-radius: 10PX 0 0 10px;
  font-size: 20px;
}

.menu li:hover {
  background-color: green;
  margin-right: 18px;
  margin-left: 1px;
}

Answer №1

One way to achieve this effect is by using CSS alone. While it may be considered a trick, in many cases JavaScript is not required for it to work effectively! (Check out the Full Page view to see it in action)

.wrapper {
  width:900px;
  height:600px;
  position:relative;
}

.item {
  position:relative;
  z-index:1;
}

.bg {
  position:absolute;
  top:0;
  left:0;
      width: 100%;
    height: 100%;
}

.bg img {
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  opacity:0;
  transition:all .3s ease;
}

.bg img:nth-child(1),
.item:nth-child(1):hover ~ .bg img:nth-child(1),
.item:nth-child(2):hover ~ .bg img:nth-child(2),
.item:nth-child(3):hover ~ .bg img:nth-child(3) {
  opacity:1;
}
<div class="wrapper">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
    <div class="bg">
      <img src="https://i.stack.imgur.com/tq1uR.jpg" />
      <img src="https://i.stack.imgur.com/ZAy9V.jpg" />
      <img src="https://i.stack.imgur.com/xfvXS.jpg" />
    </div>
  </div>

Answer №2

Instead of waiting for a CSS parent selector, you can utilize jQuery to achieve the desired effect

#container {
    width: 800px;
    height: 600px;
    background: url(http://filepic.ru/file/1441522670.jpg);
}
#container li {
    display: block;
    margin: 5px;
    float: right;
    clear: both;
    background-color: #fff;
    width: 150px;
}
#container li:hover {
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
  <ul>
    <li onmouseover="$('#container').css('background','url(http://filepic.ru/file/1441522623.jpg)');">1</li>
    <li onmouseover="$('#container').css('background','url(http://filepic.ru/file/1441522645.jpg)');">2</li>
    <li onmouseover="$('#container').css('background','url(http://filepic.ru/file/1441522653.jpg)');">3</li>
    <li onmouseover="$('#container').css('background','url(http://filepic.ru/file/1441522662.png)');">4</li>
    <li onmouseover="$('#container').css('background','url(http://filepic.ru/file/1441522670.jpg)');">5</li>
  </ul>
</div>

Answer №3

If you utilize the approach demonstrated in the code snippet below, you can effectively accomplish two tasks using the onmouseover attribute. A: Save the image source associated with each list item to separate variables, and B: Trigger a function that updates the background image of a specified div (based on its ID) by modifying the image source.

    <script type="text/javascript">
        var pictureI;
        function changeBckGrnd(){
            document.getElementById("nameOfDiv").style.backgroundImage = "url('picSrc')";

        }
    </script>
    <ul>
        <li onmouseover="picSrc=*INSERT IMAGE SOURCE HERE*; changeBckGrnd()">Image 1</li>
        <li onmouseover="picSrc=*INSERT IMAGE SOURCE HERE*; changeBckGrnd()">Image 2</li>
        <li onmouseover="picSrc=*INSERT IMAGE SOURCE HERE*; changeBckGrnd()">Image 3</li>
        <li onmouseover="picSrc=*INSERT IMAGE SOURCE HERE*; changeBckGrnd()">Image 4</li>
    </ul>

Note: Although your post was related to CSS, since you tagged javascript, I assumed you were interested in JavaScript solutions.

Answer №4

You have the option to utilize JavaScript to handle this situation.

var imagesArray = [url1,url2,......] ; // an array of background image URLs
var container = $(".menu li"); // assuming jQuery is included
function setBackgroundOnHover(imgArr,container)
{
    container.hover(function() {
        // mouse in
        for(var i=0;i<imgArr.length;i++) {
            container.eq(i).css("background-image","url("+imgArr[i]+")") ;
        }
    }, function() {
        // mouse out
        for(var i=0;i<imgArr.length;i++) {
            container.eq(i).css("background-image","") ;
        }
    });
}
setBackgroundOnHover(imagesArray, container) ;

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

Is it possible for me to hand over control to a child process and retrieve the result in Node.js?

Recently, I encountered an issue where multiple simultaneous GET requests to my Node.js server caused it to become overwhelmed and unresponsive, leading to timeouts for clients (503, service unavailable). Upon thorough performance analysis, I discovered t ...

The JSON response may be null, yet the data flows seamlessly to the success function in

Currently, I am facing an issue with Ajax. The situation is as follows: I want to check if a user is available by typing their email address. Therefore, I have created a JavaScript function that includes an Ajax script for this purpose. Here is my code: $ ...

The error stating that document.getElementById(...) is null has occurred within RSForms due to a TypeError

Issue: When clicking on the form to continue, a TypeError: document.getElementById(...) is null error occurs. Can anyone help me fix this problem? When I click on the continue button, it calls the function submitForm. <script type="text/javascript"> ...

Upon reviewing the webpage using an IPAD and AngularJS

I recently completed a web application using AngularJS and PHP. It functions smoothly on Chrome and Firefox, but it encounters loading issues on IE due to the number of JS files. To solve this problem, I will need to reduce the amount of JS files for it to ...

Having trouble executing a fetch request in Next.js

I am struggling to perform a fetch request using getStaticProps in Next.js. Despite following the documentation provided on their website, I am unable to console log the props successfully. My background is mainly in React, so I tried to adapt my approac ...

Why doesn't setting the SVG viewBox to "0 0 100 100" scale my path to 100%?

My current dilemma involves an SVG path that is only displaying at 50% of its intended size. How can I adjust it to show at 100%? Below is the code snippet in question: <div className="svgPathContainer"> <svg width="100%" he ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

Utilizing the power of $.ajax() to parse through an XML document

I have a query about working with a large XML file containing 1000 nodes. Here is the code snippet I am using: $.ajax({ type: "GET", cache: false, url: "someFile.xml", ...

Is it possible to include a shared helper text for two textfields that have been imported from MUI in a React.js project?

This snippet contains the code for my password container: .password-form-container { width: 85%; height: 7%; position: relative; top: 230px; left: 40px; display: flex; justify-content: space-between; border: 1px solid red; } <div clas ...

The lifespan of my cookie is limited

I am utilizing the jQuery.min.js from https://github.com/carhartl/jquery-cookie and my cookie code looks like this: $(function() { //hide all divs just for the purpose of this example, //you should have the divs hidden with your css //check ...

Discover the method to calculate the combined file size of multiple uploads with jquery

One of the challenges I'm facing is ensuring that users can only upload multiple files if the total size does not exceed 3GB. Is there a way I can enforce this limit? Below is the current code snippet I am using: var fileCount = 0; var showFileCo ...

Using PHP variables in HTML frameset URL for dynamic content passing

Looking for help to pass a PHP variable through a frameset URL. I've been trying different techniques without success so far. Can anyone provide some guidance? Here is an example of my code and what I have attempted: <?php $var = 2+3 ?> < ...

I attempted to post a collection of strings in ReactJS, only to receive a single string response from the Web

I was troubleshooting an issue where only one string from ReactJS was being sent to WebApi instead of an array of strings. Below is the ReactJS code snippet I used: import React, { useState } from "react"; import axios from "axios"; e ...

Learn how to easily toggle table column text visibility with a simple click

I have a working Angular 9 application where I've implemented a custom table to showcase the data. Upon clicking on a column, it triggers a custom modal dialog. The unique feature of my setup is that multiple dialog modals can be opened simultaneously ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

Start by retrieving information and then sending properties to a different component

I have been struggling with this issue for more than a week now. Despite thorough reading of the Next.js documentation and extensive online research, I still can't figure out what's wrong. It seems like I must be overlooking something important, ...

Switching carousel background image upon navigation click

I am currently working with a Bootstrap Carousel and I want to customize the background (an image) for each slide. I have 4 slides in total, each corresponding to a specific background image. <!DOCTYPE html> <html lang="en" dir="ltr ...

Error: authentication failed during npm installation due to an incorrect URL

After executing npm install @types/js-cookie@^2.2.0, an error occurred: npm install @types/js-cookie@^2.2.0 npm ERR! code E401 npm ERR! Unable to authenticate, need: Basic realm="https://pkgsprodsu3weu.app.pkgs.visualstudio.com/" npm ERR! A com ...

The phonegap page redirection is failing, as the 'location' property of the object does not function correctly

I'm attempting to implement a straightforward page redirection in PhoneGap using JavaScript. Within an iframe, I have the following code: window.parent.location("event_select.html"); Unfortunately, this approach is unsuccessful and results in the fo ...

Extracting and retrieving the value from the paramMap in Angular/JavaScript

How can we extract only the value from the router param map? Currently, the output is: authkey:af408c30-d212-4efe-933d-54606709fa32 I am interested in obtaining just the random "af408c30-d212-4efe-933d-54606709fa32" without the key "authke ...