Interactive menu with visual previews

As I work on creating a menu that displays images upon hovering, I've managed to achieve the show/hide functionality. However, there are a few additional features that I'm struggling to implement:

  1. When hovering over a submenu item, the main menu image should be hidden.
  2. If hovering over a submenu item without an image, the main menu image for that section should appear.

You can find the code below along with a CodePen link for reference: https://codepen.io/cr8tivly/pen/LYpXVGx

Thank you

HTML

<div class="container mx-auto position-relative">
  <ul class="main-menu col-6">
    <li class="nav-item parent-menu border">
      <a class="" href="">menu-1</a>
      <div class="parent-image">
        <img class="main-image" src="http://placehold.it/150/f91?text=Parent-1" alt="" />
      </div>
      <ul class="child-menu">
        <li class="nav-item">
          <a href="">smenu-1</a>
          <div class="child-image">
            <img class="" src="http://placehold.it/100/ggd" alt="" />
          </div>
        </li>

        <li class="nav-item">
          <a href="">smenu-2</a>
          <div class="child-image">
            <img class="" src="http://placehold.it/100/cdd" alt="" />
          </div>
        </li>
        <li class="nav-item">
          <a href="">smenu-3</a>
          <div class="child-image"></div>
        </li>
      </ul>
    </li>
    <li class="nav-item parent-menu">
      <a href="">menu-2</a>
      <div class="parent-image">
        <img class="main-image" src="http://placehold.it/150/green?text=Parent-2" alt="" />
      </div>
      <ul class="child-menu">
        <li class="nav-item">
          <a href="">smenu-1</a>
          <div class="child-image">
            <img class="" src="http://placehold.it/100/e00" alt="" />
          </div>
        </li>
        <li class="nav-item">
          <a href="">smenu-2</a>
          <div class="child-image">
            <img class="" src="http://placehold.it/100/dbb" alt="" />
          </div>
        </li>
        <li class="nav-item">
          <a href="">smenu-3</a>
          <div class="child-image"></div>
        </li>
      </ul>
    </li>
  </ul>
</div>

JS/JQuery

$('.parent-image').hide();
$('.parent-menu').hover(
  function(){
  $(this).find('.parent-image').show();
  },
  function() {
    $(this).find('.parent-image').last().hide();
  }
);

$('.child-image').hide();
$('.child-menu .nav-item').hover(
  function(){
  $(this).find('.child-image').show();
   $(this).find('.child-image:empty', function(){
   $('.parent-image').show();
   })

  },
  function() {
    $(this).find('.child-image').last().hide();
  }
);

CSS

.parent-image,
.child-image {
  position: absolute;
  right: 0;
  top: 0;
}`

Answer №1

Below is a recommended code snippet to achieve the desired functionality:

$('.parent-image').hide();
$('.parent-menu').hover(
  function(){
  $(this).find('.parent-image').show();
  },
  function() {
    $(this).find('.parent-image').last().hide();
  }
);

$('.child-image').hide();
$('.child-menu .nav-item').hover(
  function(){
  $(this).find('.child-image').show();
  $(this).closest('.parent-menu').find('.parent-image').hide();   

  let childImage = $(this).find('.child-image img');
  console.log(childImage.length);
   if(childImage.length==0) {
     $(this).closest('.parent-menu').find('.parent-image').show(); 
   }
    else {
      $(this).closest('.parent-menu').find('.parent-image').hide(); 
    }
/*  $(this).find('.child-image:empty', function(){
    $('.parent-image').show();
   }) */

  },
  function() {
    $(this).find('.child-image').last().hide();
  }
);

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

I am interested in utilizing Selenium to interact with a hyperlink within an HTML table

I am currently using the code snippet below to fetch data from the HTML structure provided: //findTables(driver); WebElement content = driver.findElement(By.id("tblTaskForms")); List<WebElement> elements = content.findElements(By.className("form-nam ...

Adjust the value of the flipswitch jQuery dynamically

I have been trying to dynamically change the value of a flipswitch, but it doesn't seem to be working. <div id="header-connection-icon"> <input type="checkbox" data-mini="true" data-role="flipswitch" name="flip-checkbox-1" id="flip1" ...

What is the best way to automatically update the contents of a div that contains PHP variables

Recently, I created a new page called queries.php <?php require("connection.inc.php"); $query = "SELECT SUM(john), SUM(robert), COUNT(school) FROM election"; $result = mysql_db_query($db, $query, $connection) or die("query error!"); $data = mysql_fetc ...

Showing a heading based on a value in Angular: A Complete Guide

I am attempting to dynamically change the title based on the item's _id value. I have stored the item in the component. Here is the HTML code I am using: <h1 mat-dialog-title>{{item._id ? "Update" : "Add"}} animal</h1> Below is my dialog ...

What is the best way to insert a line break following a font awesome icon within a list?

My goal is to design a menu similar to LinkedIn's, featuring buttons made from icons positioned above text. However, I'm facing difficulty in inserting line breaks in CSS format after my FontAwesome icons. Despite having 'display:block' ...

Error in Mathquill: Unable to access the 'prototype' property because it is undefined

I'm currently in the process of integrating MathQuill into a project I'm developing. After installing the package through NPM (npm install mathquill), I included the following <script> tags in the <head>: <script src="../node_ ...

Show off JSON images on your website using jQuery

I'm struggling to showcase JSON array data with jQuery. Despite referring to various online examples, I can't seem to shake off the errors and issues. Whenever I attempt to confirm(val.image);, a pop-up emerges stating: "unidentified". The jQue ...

Looking for a JavaScript snippet to insert the word "Search" into an empty DIV element with the specified id attribute

I am trying to insert the word "Search" into an empty input field with the id "ReportQuery" using JavaScript. Unfortunately, I do not have access to the HTML code directly. How can I achieve this task through coding? Below is the snippet of code that nee ...

Lack of y data in the Highcharts

I am facing an issue with retrieving yAxis data in Highcharts. You can view the fiddle at https://jsfiddle.net/LLExL/6496/. I have loaded Highcharts using the code below. $(function () { $('#RankingReportsHistory').highcharts( ...

Creating a tool for checking domain name availability

Looking to create a domain name availability checker, but struggling to find the necessary information. My goal is to simply determine if a domain is still available or not. I've already set up a form on my website () and used jQuery to gather the dom ...

The recursive function halted its execution following the initial iteration

Situation To ensure server efficiency, I have set up a system where multiple websites are updated using Ajax calls sequentially. I've created a recursive function that triggers itself every time an Ajax call is successfully completed. Problem Howev ...

What is the best way to create a basic accordion using only certain table rows?

I am faced with the task of transforming a HTML table that lists various items. Each <tr> within the table contains a unique title element, but there are cases where rows can share the same title indicating their relation. My goal is to implement jQu ...

Displaying related data in jqGrid using foreign keys

My jqGrid is connected to a JSON datasource provided by a WCF web service. The WCF method retrieves a list of ids showing the relationship between a user, branch, and role. For instance, a user can have different roles in different branches. [{"entityHash ...

What could be causing my absolutely positioned div to be hidden from view?

I'm working on designing a slideout slideshow with three images and content that looks like papers hidden in folders, complete with a handle at the top or bottom of each folder displaying its name. Here's an example of what I'm envisioning: ...

Strategies for extracting data from multiple Textareas in React

I am facing an issue with a form that contains multiple textarea elements (specifically 3). The problem is that when I type in one textarea, the content is automatically filled and updated in the other textareas as well. This behavior is not desired. I h ...

Tracking User IDs across different domains with Piwik: a step-by-step guide using PHP and JavaScript

Is there a way to connect the IP address of the current visitor to a specific user ID using PHP in Piwik tracking, and ensure this connection is maintained across multiple (sub)domains? I have multiple (sub)domains and I want to assign a unique UserID to ...

What is the most efficient way to quickly check for the absence of a value

Here is an example of some code I have: var process = function(next){ //do stuff if(typeof next != 'undefined') { next(a, b, c, d, e); } } I'm getting tired of using typeof repeatedly. Is there a way to create a global function th ...

What is the process for including multiple placeholders in an HTML document?

I have created a software application. <div id="todo-app"> <label class="todo-label" for="new-todo">What is your goal for today?</label> <input type="text" id="new-todo" class="todo-input" placeholder="go for a run" ...

Any suggestions on how to address vulnerabilities in npm when upgrading the main dependency version is not an option?

I recently ran the npm audit --production command and found a high-risk vulnerability related to the snowflake-sdk dependency. After checking the snowflake github page, I noticed that the package.json file includes "requestretry": "^6.0.0&qu ...

The method of document.getElementsByName does not provide any results

I am a beginner in using python flask and understanding the MVC concept. My goal is to display the selected option in a dropdown list. Below is my list defined in a .py function. @app.route('/', methods=['GET']) def dropdown2(): ...