Changing background images with CSS upon mouse hover

I've been attempting to create a mega menu-like design, but so far, I haven't had much success. Below is the code I've been using for the simplest possible result.

The setup involves two divs - one for an image and another for the menu. The goal is to have the image change when hovering over a link in the menu. I'm open to using either CSS or JavaScript to achieve this effect.

Here is the HTML code:

<div>
    <div id="img_div"></div>
    <div id="links_div">
        <ul>
            <li><a href="">Show image 1</a></li>
            <li><a href="">Show image 2</a></li>
            <li><a href="">Show image 3</a></li>
            <li><a href="">Show image 4</a></li>
            <li><a href="">Show image 5</a></li>
        </ul>
    </div>
</div>

And here is the CSS code:

<style>
 #img_div{
    height: 200px;
    width: 200px;
    background: url("images/default.jpg");
    float: left;
}
 #links_div{
    float: left;
    height: 200px;
    width: 200px;
}
ul{
    margin: 0;
    padding: 0;
    list-style-type: none;
}
ul li{
    display: block;
}
ul li a{
}
</style>

Answer №1

I have developed a sample code that utilizes the click event. Let me know if this meets your requirements. If I've understood correctly, you could potentially replace "click" with "hover" based on your problem statement.

Update: Implementing mouse events instead of click events

$(document).ready(function() {
  $("#links_div a").on("mouseenter", function() {    
    $("#img_div").addClass($(this).attr('data-class'));
  });
  
  $("#links_div a").on("mouseleave", function() {
    $("#img_div").removeClass($(this).attr('data-class'));
  });
});
#img_div {
  height: 200px;
  width: 200px;
  background: url("http://placehold.it/200x200");
}
#img_div.a {
  background: url("http://placehold.it/200x200?text=a");
}
#img_div.b {
  background: url("http://placehold.it/200x200?text=b");
}
#img_div.c {
  background: url("http://placehold.it/200x200?text=c");
}
#img_div.d {
  background: url("http://placehold.it/200x200?text=d");
}
#img_div.e {
  background: url("http://placehold.it/200x200?text=e");
}
#links_div {
  float: left;
  height: 200px;
  width: 200px;
}
ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
ul li {
  display: block;
}
ul li a {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div id="img_div"></div>
  <div id="links_div">
    <ul>
      <li><a href="javascript:void(0)" data-class="a">Show image 1</a>

      </li>
      <li><a href="javascript:void(0)" data-class="b">Show image 2</a>

      </li>
      <li><a href="javascript:void(0)" data-class="c">Show image 3</a>

      </li>
      <li><a href="javascript:void(0)" data-class="d">Show image 4</a>

      </li>
      <li><a href="javascript:void(0)" data-class="e">Show image 5</a>

      </li>
    </ul>
  </div>
</div>

Answer №2

Implement a CSS rule that exclusively targets the div with the class altImage:

#img_div.altImage {
    background: url("images/alt.jpg");
}

Incorporate JavaScript to assign a class to the div when hovered over:

var links = document.getElementById("links_div");

links.addEventListener("mouseenter", function(e) {
    document.getElementById("img_div").classList.add("altImage");
});

links.addEventListener("mouseleave", function(e) {
    document.getElementById("img_div").classList.remove("altImage");
});

This approach should be effective

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

Tips on separating/callback functions based on earlier variables

Breaking Down Callback Functions Based on Previous Variables I am trying to figure out how to efficiently break down callback functions that depend on variables defined earlier in the code. Currently, my code resembles a "callback hell" due to my lack of ...

Perform two functions in order using jQuery within a loop

Just dipping my toes in the waters of Javascript. Please go easy on me :) I'm working with two functions that both involve making jQuery requests within for loops. Here's an example: function x(y,z) { for (var i = 0; i < y; i ++) { $.a ...

The jQuery Mobile click event is limited to firing only once, as the DOM undergoes changes as a result of the initial

I am attempting to attach a click event using jQuery Mobile in a multi-page setting (this page is not the main page): HTML <div data-role="page" id="thirdPage"> <div class="wrapper"> <div class="segment"></div> < ...

How can I add text to the title of a border using Bootstrap5?

I am attempting to create a design where text appears within the border of an element. I am currently utilizing Bootstrap 5 and jQuery for this project. Despite my efforts with fieldset and legend elements, I have not been successful in achieving the desir ...

Combining multiple AngularJS expressions to form a URL within an interpolation statement

While this explanation may be lengthy, I appreciate your patience as I try to articulate the issue at hand. The error I'm currently encountering is as follows: Error: [$interpolate:noconcat] Error while interpolating: Strict Contextual Escaping disa ...

Utilize MySQL to populate highcharts with data

Learning the ropes of web programming, I have a personal project to monitor expenses. Simply put, my database stores data on total expenditures for this month and last month. I am able to display it manually (via echo), but I'm struggling to pass the ...

Having trouble integrating SVG icons into my Angular project

I'm encountering an issue with adding icons that I've designed in Figma to my web application. Some of the icons are displaying correctly while others are not. Here is the code snippet I am using to add the icons: .dx-icon-info { mask-image: ...

How to remove checkbox border using HTML, JavaScript, and CSS

Is it possible to remove the square border from a checkbox in HTML? ...

Methods for anchoring an element at the bottom of a square container div

* { box-sizing: border-box; } .publication { display: flex; width: 100%; margin-top: 6%; } .bottom1, .bottom2 { display: flex; flex-direction: column; ...

What are the implications of making more than 8 ajax calls simultaneously when a single submit button event is triggered?

I am currently working on a project that involves the use of 8 dropdown menus. These dropdowns are optional, meaning that users can choose to select all 8, or just a few based on their requirements. Each dropdown operates independently, and I have written ...

Unable to add to content that is generated dynamically

Upon loading the page, I noticed that the #navbarUsername field remains empty while all other scripts below it run correctly. Despite attempting to use $(document).on('ready', '#navbarUsername', function () {..., this did not resolve th ...

Discovering a specific value within a JSON stringified array

I am looking for a specific value within a JSON stringify array [{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":" ...

Is it possible for Monaco Editor to accommodate nested tokens?

I have configured a custom language in the monaco editor, with two root tokens: [/^\[?[e|E][r|R][r|R][o|O][r|R]\]?\s.*/, 'error'], [/\d{1,4}(-|\/|\.|:)\d{1,2}\1\d{1,4}/, 'time'], Using this ...

The file field appears to be empty when sending a multipart/form-data request via AJAX

I'm encountering an issue when attempting to submit a multipart/form-data using AJAX. Here is the HTML code snippet: <form id='form_foto' method='post' enctype='multipart/form-data'> <input type='hidden ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Ensuring the accuracy of input data in all input fields with the help of dojo

1)In my Dojo widget, I have two additional widgets loaded inside. If I need to clear all text boxes within the widget, I currently use this method: this.myAttachPoint.value="". Is there an alternative code that can achieve the same result without adding ...

Arrange records in ascending order by phone number when multiple are returned on the same date

Currently, I am working on an Angular application that is designed to keep track of tuxedo rentals. The main feature of the app is a table that displays information from an array stored in the controller. The initial task I completed was listing the items ...

Is d3 Version pretending to be a superior version?

I have encountered an issue with my project that involved using d3 v5.5.0. After transferring it to a different computer and running npm install, the application now seems to be recognizing d3 as a higher version? A crucial part of my program relies on th ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

Mastering AJAX requests in Zend Framework

I'm facing a challenge in integrating an AJAX search function with the Zend Framework. My Controller and Action look like this: class IndexController extends Zend_Controller_Action { public function indexSearchAction() { $this-> ...