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 technique for adding a blur effect to the top and right side of a div element?

Here is a link to my fiddle: https://jsfiddle.net/aod4rmx8/ .background{ position: absolute; left: 0; width:50%; right: 0; bottom: 0; top:0; background-color: #000; /*box-shadow: 100px 0 40px 6px rgba(0, 0, 0, 1);*/ -webk ...

Automated updating of Google Map markers

I am looking for a way to continuously update the marker on my Google Map to reflect my current position every 15 seconds using Jquery. Can anyone provide guidance on how to achieve this? Here is my code snippet: var x=document.getElementById("message"); ...

Tips for embedding the <img> element inside the <a> element

I'm attempting to place an image within a hyperlink tag. Current code: <div class="Sample"> <a href="http://www.Sample.com"> <img src="http://www.Sample.com/Sloth.jpg"> </a> </div> I wish to add <img class= ...

Issue with implementing autocomplete using AJAX and PHP for multiple input fields

HTML code: <table> <tr> <td align="center"> <label for="InputBox1"><b>~</b><font color="red">*</font>: &nbsp;</label> </td> </tr> <tr> <td align="center"> <div id="1"> ...

Displaying a div on click is simple with CSS and JQuery, but what if you want it to stay visible even after a second click? By utilizing classes within <li> tags instead of buttons

My current code involves clicking on a menu, which should reveal a list where each item has a corresponding section that slides down and slides back up when clicked. However, only the sliding down functionality is working at the moment. I'm new to jQu ...

Enhance multiple select functionality

I am currently working on a function to dynamically update the options in a select input based on the selection made in another select input. Specifically, when Method1 is selected, I want only the options 1A, 1B, and 1C to appear in the second select. S ...

What potential issue could this code be causing with repeated form submissions?

Trying to implement AJAX form submission using PHP code: <!doctype html> <html> <head> <meta charset='utf-8'> <script type='text/javascript' src="./js/jquery.min.js"></script> ...

The display and concealment of a div will shift positions based on the sequence in which its associated buttons are clicked

I am in need of assistance with coding (I am still learning, so please excuse any syntax errors). What I am trying to achieve is having two buttons (button A and button B) that can toggle the visibility of their respective divs (div A and div B), which sh ...

interactive textbox created with the combination of javascript and php

Hello, I am new to JavaScript and jQuery. I am trying to create a dynamic text box using JavaScript that can add and remove rows. When I press the add button, it works well, but when I pressed delete, it deleted the entire table. Below is my JavaScript fu ...

The issue with Internet Explorer failing to adhere to the restrictions set on maximum width and

I'm attempting to scale my images precisely using CSS: HTML: <div id="thumbnail-container"> <img src="sample-pic.jpg"/> </div> CSS: #thumbnail-container img { max-height: 230px; max-width: 200px; } In this scenario, ...

Obtaining the jqXHR object from a script request loaded within the <head> tag using the <script> tag

Is it possible to retrieve the jqXHR object when a script loaded from a script tag within the head tag? function loadScript(url){ const script = document.createElement("script"); script.src = url; // This line will load the script in the ...

Is it possible to remove without delay using .ignore()?

Check out this demonstration: <div id='example'> Hello </div> $('#example').fadeOut(600).delay(600).remove(); I am trying to fade out an element and then remove it, but it seems like the .remove() function is not hono ...

Creating a personalized error page with the .htaccess file

I want to create personalized error pages for different errors This is the layout of my directory: .htaccess error_pages: error_400.html error_401.html error_404.html ...

Retrieving data from a database using Ajax

As I develop a webpage that dynamically loads images from a database as the user scrolls, I encounter an issue where newly added images are displayed again when more images are fetched from the database. How can I prevent this from happening? Here is the ...

Conceal the sidebar menu by clicking anywhere outside of the menu bar or the designated button

I attempted to create a menu similar to the semantic UI, but so far I have only been able to click the menu button to open and close the menu. I am using a toggle class to display the sidebar, but I'm unsure if this approach is entirely correct: < ...

Generating dynamic ID attribute through JavaScript

Here is a portion of my recursively rendered partial view: <ul> @if (item != null) { <li id="@item.Id"> @item.ActionName @if (item.CMSModels.Count > 0) { @Html.Partial("Ch ...

"Discover the secrets of flipping a webpage just like turning the pages of

I recently designed a basic website with 4 separate pages. The homepage includes navigation links for each page, such as - Page1 page2 Page3 Page4 My goal now is to create a feature where clicking on any of these links will open the corresponding page wi ...

The hyperlink function is not operational in Gmail attachments

Using an anchor tag to navigate to a specific section within the same page works perfectly when the HTML file is on my local machine. However, when I attach the file in Gmail and open the attachment, it doesn't work. Why is this happening? How can I m ...

I am experiencing some challenges with my code as the Jquery Ajax function does not seem to be functioning correctly. Can

I am trying to incorporate a for loop (or `do/while loop) in my code, but unfortunately, it is not functioning as expected. The current setup is only working for a single item, and the goal is to have multiple items on a single invoice by utilizing the lo ...

The challenge of harmonizing variables in PHP and JavaScript

I have a PHP script that generates an HTML table displaying data from a MySQL database. <?php include 'connexion.php'; session_start(); $idfirm = $_REQUEST['idfirm']; $namefirm = $_REQUEST['namefirm']; The table rows are ...