Switch images when hovering

I currently have two dropdown menus called NEW and SHOP.

When I hover over the New Menu 1, it should display the corresponding image. Similarly, when hovering over New Menu 2, the related image should be shown in a div with the ".menu-viewer" class.

While this functionality is working, it is also changing the image of the shop menu, which is not intended.

Furthermore, the default image for the shop menu is not displayed automatically.

Please take a look at the Fiddle I've set up and let me know what mistake I might be making.

If my explanation is unclear or confusing, please don't hesitate to ask for clarification.

https://jsfiddle.net/cancerian73/qwtono6c/

 var $img = $('.menu-viewer img'),
 dsrc = $img.attr('src');
 $('.menu-list ul li a').hover(function() {
 var $this = $(this).addClass('hover');
  $img.attr('src', $this.data('image'));
 }, function() {
 $(this).removeClass('hover');
$img.attr('src', dsrc);
 });


 $('.menu-list ul li').bind('mouseenter focusin',function() {
 $($(this).attr('href')).show();
 }).bind('mouseleave focusout',function() {
 $($(this).attr('href')).hide();
 });

Answer №1

To update the image in the current block, I've utilized jQuery's closest function to locate the nearest ancestor megamenu and modify the image accordingly:

$('.menu-list ul li a').hover(function() {
  var $this = $(this).addClass('hover'),
    $img = $this.closest('.megamenu').find('.menu-viewer img');
    
  $this.data('original', $img.attr('src'));
  $img.attr('src', $this.data('image'));
}, function() {
  var $this = $(this),
    $img = $this.closest('.megamenu').find('.menu-viewer img');
  
  $this.removeClass('hover');
  $img.attr('src', $this.data('original'));
});
ul {
  list-style: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
  <a href="javascript:void(0)">NEW MENU</a>
  <div class="megamenu clearfix">
    <div class="grid-container">
      <div class="grid-x align-center align-middle">
        <div class="cell small-8 shrink">
          <div class="grid-x">
            <div class="cell small-4">
              <div class="menu-list">
                <ul>
                  <li id="menulist1"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 1">NEW MENU 1</a></li>
                  <li id="menulist2"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 2">NEW MENU 2</a></li>
                </ul>
              </div>
            </div>
            <div class="cell small-8">
              <div class="menu-viewer"><img src="http://via.placeholder.com/350x150?text=NEW MENU 1" alt="Cruise Collection" /></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</li>
<li>
  <a href="javascript:void(0)">Shop</a>
  <div class="megamenu clearfix">
    <div class="grid-container">
      <div class="grid-x align-center align-middle">
        <div class="cell small-8 shrink">
          <div class="grid-x">
            <div class="cell small-2">
              <div class="menu-list">
                <ul>
                  <li id="menulist3"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 1">SHOP 1</a></li>
                  <li id="menulist4"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 2">SHOP 2</a></li>
                  <li id="menulist5"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 3">SHOP 3</a></li>
                </ul>
              </div>
            </div>
            <div class="cell small-8">
              <div class="menu-viewer">
                <img src="http://via.placeholder.com/350x150?text=SHOP1" alt="Cruise Collection">
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</li>

Adjusted based on feedback

$('.menu-list ul li a').hover(function() {
  var $this = $(this).addClass('hover'),
    $images = $this.closest('.megamenu').find('.menu-viewer img');

  $images.eq(0).addClass('hidden');
  $images.eq(1).attr('src', $this.data('image')).removeClass('hidden');

}, function() {
  var $this = $(this),
    $images = $this.closest('.megamenu').find('.menu-viewer img');
    
  $images.eq(1).addClass('hidden');
  $images.eq(0).removeClass('hidden');
});
ul {
  list-style: none
}

.menu-viewer {
  position: relative;
}

.hidden {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}

img {
  position: relative;
  opacity: 1;
  transition: opacity 0.75s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
  <a href="javascript:void(0)">NEW MENU</a>
  <div class="megamenu clearfix">
    <div class="grid-container">
      <div class="grid-x align-center align-middle">
        <div class="cell small-8 shrink">
          <div class="grid-x">
            <div class="cell small-4">
              <div class="menu-list">
                <ul>
                  <li id="menulist1"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 1">NEW MENU 1</a></li>
                  <li id="menulist2"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 2">NEW MENU 2</a></li>
                </ul>
              </div>
            </div>
            <div class="cell small-8">
              <div class="menu-viewer"><img src="http://via.placeholder.com/350x150?text=NEW MENU 1" alt="Cruise Collection" />
                <img class="hidden" src="http://via.placeholder.com/350x150?text=NEW MENU 1" alt="Cruise Collection" /></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</li>
<li>
  <a href="javascript:void(0)">Shop</a>
  <div class="megamenu clearfix">
    <div class="grid-container">
      <div class="grid-x align-center align-middle">
        <div class="cell small-8 shrink">
          <div class="grid-x">
            <div class="cell small-2">
              <div class="menu-list">
                <ul>
                  <li id="menulist3"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 1">SHOP 1</a></li>
                  <li id="menulist4"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 2">SHOP 2</a></li>
                  <li id="menulist5"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 3">SHOP 3</a></li>
                </ul>
              </div>
            </div>
            <div class="cell small-8">
              <div class="menu-viewer">
                <img src="http://via.placeholder.com/350x150?text=SHOP1" alt="Cruise Collection">
                <img class="hidden" src="http://via.placeholder.com/350x150?text=SHOP1" alt="Cruise Collection">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</li>

Answer №2

For assistance with CSS, consider adding an index variable in case you want to incorporate more images in the future. This setup requires each anchor to have an id in the format of menulist + <number>. Additionally, I adjusted it so that when you move your mouse away from the link, the menu image will not revert back to its previous state. I'm not sure if this aligns with your intended functionality, but it feels more intuitive in this manner.

Feel free to give it a try!

$('.menu-list ul li a').mouseenter(function() {
    var $this = $(this).addClass('hover');
    var index = $this.parent().attr('id').match(/menulist(.+)/)[1];
    
    $this.closest('.cell').siblings('.small-8:first').find('img:nth-child('+index+')').addClass('active').siblings('img').removeClass('active');
     
  });
ul{list-style:none}

img.cruise-coll{
  display: none
}

img.cruise-coll.active{
  display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
   <a href="javascript:void(0)">NEW MENU</a>
   <div class="megamenu clearfix">
      <div class="grid-container">
         <div class="grid-x align-center align-middle">
            <div class="cell small-8 shrink">
               <div class="grid-x">
                  <div class="cell small-4">
                     <div class="menu-list">
                        <ul>
                           <li id="menulist1"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 1">NEW MENU 1</a></li>
                           <li id="menulist2"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 2">NEW MENU 2</a></li>
                           <li id="menulist3"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 2">NEW MENU 3</a></li>
                           <li id="menulist4"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 2">NEW MENU 4</a></li>
                           <li id="menulist5"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=NEW MENU 2">NEW MENU 5</a></li>
                        </ul>
                     </div>
                  </div>
                  <div class="cell small-8">
                     <div class="menu-viewer">
                     <img class="cruise-coll active" src="http://via.placeholder.com/350x150?text=NEW MENU 1" alt="Cruise Collection"/>
                     <img class="cruise-coll" src="http://via.placeholder.com/350x150?text=NEW MENU 2" alt="Cruise Collection"/>
                     <img class="cruise-coll" src="http://via.placeholder.com/350x150?text=NEW MENU 3" alt="Cruise Collection"/>
                     <img class="cruise-coll" src="http://via.placeholder.com/350x150?text=NEW MENU 4" alt="Cruise Collection"/>
                     <img class="cruise-coll" src="http://via.placeholder.com/350x150?text=NEW MENU 5" alt="Cruise Collection"/></div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</li>
<li>
   <a href="javascript:void(0)">Shop</a>
   <div class="megamenu clearfix">
      <div class="grid-container">
         <div class="grid-x align-center align-middle">
            <div class="cell small-8 shrink">
               <div class="grid-x">
                  <div class="cell small-2">
                     <div class="menu-list">
                        <ul>
                           <li id="menulist3"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 1">SHOP 1</a></li>
                           <li id="menulist4"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 2">SHOP 2</a></li>
                           <li id="menulist5"><a href="javascript:void(0)" data-image="http://via.placeholder.com/350x150?text=SHOP 3">SHOP 3</a></li>
                        </ul>
                     </div>
                  </div>
                  <div class="cell small-8">
                     <div class="menu-viewer">
                        <img src="http://via.placeholder.com/350x150?text=SHOP1" alt="Cruise Collection">
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</li>
</ul>

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

What is the best way to horizontally center a div while ensuring the content within the div stays aligned?

I'm attempting to align a div in the center while maintaining the position of its contents. Check out my code snippet: <style> .wrap{ position: relative; } .character{ position: absolute; bottom: -10%; left: 0; heigh ...

What impact does including a parent View Tag have on the styling in React Native?

Why does adding a View parent break my styles? Could React Native's View tag have default styles that I'm not aware of? Displayed below is the Button component along with screenshots demonstrating the difference when using and not using the View ...

An error has occurred with Datatables: dtSettings is not defined

I have successfully implemented data-tables with fixed columns on my project. The first data-table, patients_report, is working perfectly fine. However, the second one, visitation_report, is encountering some issues. Can someone please advise me on how t ...

Javascript Object and Conditional Statement

I am working on a Dygraph object creation script that includes a data variable. However, I want to avoid passing in this variable for older browsers. Here is the code snippet: function prime() { g = new Dygraph( document.getElementById("g"), d ...

Sending form data using Ajax in codeigniter

I am encountering an error while attempting to submit a form using ajax in codeIgniter. Below is the view code that I have: <div class="form-group input-control"> <p id="error1" style="display: none; color: green"><b>Registered Succ ...

Retrieve a specific child element by clicking on a custom control on the map

I have a container element with three child spans. Using JQuery, I can determine which child was clicked when the container is clicked by utilizing the following function: $('.unitContainer').on('click','span',function(){ ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

Tips for creating a hover effect on an icon within a CSS grid

I've just started learning to code and wanted to create a component for previewing/displaying a project I'm working on. I've been attempting to add a hover effect to my links such as the GitHubIcon and LaunchIcon, but so far, it's not w ...

Use a text link to upload a file instead of using an input field

While I've seen some discussions on this topic already, the conflicting answers have left me uncertain. Is there a foolproof method for triggering file upload without using an input field? Essentially, I'd like to create a div with an icon and te ...

Create an input field dynamically by utilizing the append method in jQuery

Concern: As part of an edit page, I am working on appending an input field from a modal window to an existing panel while retaining the format of the rest of the fields. The user is currently able to create and add the new field using the code provided in ...

Implementing dynamic AngularJS functionality within an older HTML structure using JQuery

I am facing an issue while trying to load dynamic content using AngularJS. In my system, I have legacy pages that utilize JQuery for dynamic loading. However, as I am developing new features with AngularJS, I am encountering the same problem with dynamic ...

Adjust the sliders according to the current time

I am looking to display different sliders based on the time of day. For instance, 'slider set 1' from 0-9am, 'slider set 2' from 9am-12pm, and so forth. I am new to java script and need assistance in solving this challenge. Below is the ...

How to make an Ajax "POST" request to the server using jQuery or AngularJS without sending any parameter data

"Execute a 'POST' request to the server by using the code provided below However, the parameter data is not being sent to the server. I have attempted both the jQuery Way and var request = $.ajax({ url: baseUrl, type:'post', da ...

Having issues transferring the variable from JavaScript to PHP?

When attempting to pass a variable via AJAX request in JavaScript, I am encountering an issue where the variable is not being received in my PHP file. I'm unsure of where the problem lies. Can anyone help? JavaScript code var build = { m_count : ...

HTML form submission with a grid of multiple choice options

I have created my own multiple choice grid: <div style="overflow-x:auto;"> <table class="w-100"> <tr> <td class="border"></td> <td class="border">Yes</td> <td class="border">No</ ...

Is there a way to incorporate HTML code into a fullCalendar 4 event title?

Is it possible to add HTML content to an event title using eventRender in FullCalendar version 4? document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new ...

Use jQuery to remove an ID from an element using AJAX to interact with a database, then update

Hello, I am currently using jQuery to retrieve ids of multiple fields with ajax and send the data to be deleted via php. Despite being able to delete one item successfully, I am struggling to remove other ids. For example: Within a for loop that retrieves ...

Using jQuery combogrid to automatically target and populate input box upon row selection

I have implemented combogrid functionality from https://github.com/powderblue/jquery-combogrid to display suggestions while typing. $(".stresses").combogrid({ url: '/index/stresssearch', debug: true, colModel: [{'col ...

`Text-overflow ellipsis should function consistently across both Firefox and Chrome browsers`

A design has been created to showcase captions for articles and their respective statuses. The article name box has a fixed width, with text-overflow:ellipsis applied to trim excessively long names. Additionally, a light grey dotted line is added at the en ...

What is the maximum size for an ajax post request?

I am in the process of converting an old MSAccess mdb file. I am attempting to transfer data from the server into a 2D array, but I believe I may be approaching it incorrectly. Here is a line from the JQuery code on the main page: $.ajax({ url: "clie ...