Adjust the appearance of an element in a different parent when hovering over a specific element with a matching index

I have implemented a menu on my site in two different ways - one using text and the other using pictures. Users can click on both types of menus.

Now, I am looking to create an interactive feature where hovering over a specific item in the text menu (such as number 2) will automatically change the picture with the corresponding number (e.g. image under number 2).

Here is the code for the text menu:

<ul>
   <li class="page_item">
     <a href="#">Test 1</a>
   </li>
   <li class="page_item">
     <a href="#">Test 2</a>
   </li>
</ul>

And here is the code for the Pictures menu:

<div class="project__card project__card-design">

<div class="project__card-design-bigelem">
 <a href="#" class="project__img-link project__img-fromdesign" style="background-image: url(https://images.pexels.com/photos/927022/pexels-photo-927022.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500);"></a>
</div>
<div class="project__card-design-bigelem">
 <a href="#" class="project__img-link project__img-fromdesign" style="background-image: url(https://images.pexels.com/photos/927022/pexels-photo-927022.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500);"></a>
</div>
<div class="project__card-design-bigelem">
 <a href="#" class="project__img-link project__img-fromdesign" style="background-image: url(https://images.pexels.com/photos/927022/pexels-photo-927022.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500);"></a>
</div>

</div>

If you want to see how the Picture and text menus look together, check out this screen shot with Picture and text menu.

I would greatly appreciate any assistance or ideas on how to achieve this interactive functionality!

I have been searching for solutions that could help me identify the highlighted element by its number but haven't had much success so far. Any help would be highly appreciated!

Answer №1

If you want to implement this behavior, here's how you can do it:

When hovering over a specific element, you can get the index of that element and use it to match with another element in the navigation. Once matched, you can choose to perform any action after the matching is completed.

$(".js-hover").on("mouseenter", function () {
  const hoverIndex = $(this).index();
  const $imageListItems = $(".image-list > li");

  $imageListItems.removeClass("image-list__item--selected");
  $imageListItems.eq(hoverIndex).addClass("image-list__item--selected");
});
.image-list__item--selected {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="list">
  <li class="js-hover">text</li>
  <li class="js-hover">text</li>
  <li class="js-hover">text</li>
  <li class="js-hover">text</li>
</ul>

<ul class="image-list">
  <li>image1</li>
  <li>image2</li>
  <li>image3</li>
  <li>image4</li>
</ul>

Answer №2

Looking for a pure JavaScript solution that works on elements not directly related by parent-child relationships using IDs? Here's an example:

HTML

<li id="child1" onmouseenter="customHover(event)" onmouseleave="handleMouseLeave(event)"></li>
<div id="parent1"> </div>
<li id="child2" onmouseenter="customHover(event)" onmouseleave="handleMouseLeave(event)"></li>
<div id="parent2"> </div>
<li id="child3" onmouseenter="customHover(event)" onmouseleave="handleMouseLeave(event)"></li>
<div id="parent3"> </div>

JavaScript

function customHover(e){
  let id = e.target.id;
  let idNumber = id.slice(id.length - 1);
  document.getElementById(`parent${idNumber}`).style.border = '1px solid red';
}

function handleMouseLeave(e){
  let id = e.target.id;
  let idNumber = id.slice(id.length - 1);
  document.getElementById(`parent${idNumber}`).style.border = 'unset'; // Any necessary style changes can be made here
}

Answer №3

There are numerous solutions available, both with and without the use of libraries. Consider utilizing jQuery if feasible, or explore alternatives such as addeventlistener (the more advanced approach).

https://api.jquery.com/hover/

This link provides a good example of how to achieve your desired outcome.

var pageitemcount=0;
$( ".page_item" ).hover(function() {
  pageitemcount++;
$.post("/mypageitemcounter.php",{pageitemcount:pageitemcount});
$(this).parent().append( $( "<span>"+pageitemcount+"</span>" ) );
});

The aforementioned code snippet is tailored for PHP but can also be adapted for use in a plugin. If you're working within a WordPress environment, it's essential to familiarize yourself with creating WP plugins. Experimenting in a separate environment before incorporating changes into your custom WP plugin is advised. Avoid modifying existing plugins or themes whenever possible, as this may lead to complications down the line. In the context of WordPress development, constructing a personalized plugin is highly recommended. If suitable, label your query under "wp-plugin".

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

An issue occurred while the request was being transported or processed, resulting in Error code 10 at Path /wardeninit

Currently, I am attempting to pass an object (specifically the contents of a row from a sheet) to an apps script template. The screenshot displays the actual row. https://i.stack.imgur.com/IzMrn.png The function in my apps script consists of the followin ...

CSS selector targeting an element based on the value of its table border

Is there a way to target a table on a webpage using a CSS selector? The table structure looks like this: <table border="1" width="560" cellspacing="0"> <tr> <td height="28" colspan="3" bgcolor="#FFFFF...> </tr> </table ...

Update the CSS styles using properties specified within an object

Is it possible to dynamically apply CSS styles stored in a JavaScript object to elements? For instance, can we change the width and background of a basic <div> element: <div id="box"></div> <button id="btn">click me</button> ...

Storing data using angular-file-upload

In my application, I am utilizing the "angular-file-upload" library to save a file. Here is the code snippet that I am using: $scope.submitForm = function(valid, commit, file) { file.upload = Upload.upload({ url: '/tmp', data ...

Refresh the click event on a newly added element in the backbone framework

As a newcomer to backbone.js and using CodeIgniter as my PHP Framework, I encountered a challenge while developing an existing system that uses a backbone.js library. The problem is straightforward if approached with jQuery, but due to the use of backbone ...

Sending the parameter with the URL and receiving the response in return

Can the result be retrieved by calling a URL and sending specific parameters with it? For instance, if I pass two numbers along with the URL, can I receive the sum in return? The addition operation is carried out on the page being called upon. ...

Obtaining a Variable Element through Selector

When working with Puppeteer, I am faced with the challenge of clicking on a web button that has a dynamic id like: #product-6852370-Size. Typically, I would use the following code: page.click('#product-6852370-Size'); However, the number withi ...

Guidance on Implementing a Delay and FadeIn Effect for AJAX Responses from JSON Iterator

How can I iterate over the following foreach loop with a delay between each item and a fadeIn effect on each? I am debating whether .append() is the most suitable function to use since I want to load a templated div with the class #fan for each person in ...

Learn how to use Bootstrap to position my component below another component on the webpage

Understanding the basics of Bootstrap and how to assign sizes to columns is one thing, but I seem to be stuck on a simple use case. Here is the scenario: I have two components for a Todo list application: Component 'New Todo' (Form Input field ...

Using Angular 6's httpClient to securely post data with credentials

I am currently working with a piece of code that is responsible for posting data in order to create a new data record. This code resides within a service: Take a look at the snippet below: import { Injectable } from '@angular/core'; import { H ...

WordPress AJAX call results in a response code of zero

TL;DR: Unique - Go straight to code below for issue. You can view the demo I am working on by following this link. In my `functions.php` file, I first localize my script: function ajaxurl(){ wp_enqueue_script( 'product-selector', get_templ ...

Prevent touch swiping on Bootstrap carousel in Safari

After adding the code snippet below to my Bootstrap carousel, I've encountered an issue where I am unable to disable touch swiping on iOS devices for the carousel. <div id="infinityWarContentWrapper" class="carousel slide carousel-sy ...

Error: JSON parsing failed due to an unexpected character 'W' at the beginning

I am encountering an issue while sending a POST Request through the API in JavaScript. The method I have been using for multiple POST Requests is now displaying the error message: SyntaxError: Unexpected token W in JSON at position 0 Below is the snippet ...

Detecting browser reload in React/Typescript: A guide

Is there a way to determine if the browser has been reloaded? I've explored various solutions, but most suggest using code like this: const typeOfNavigation = (performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming).type ...

Unable to showcase information in a jQuery UI popup through AJAX when initially presented

I'm trying to display reviews from my database on a jQuery UI dialog box upon loading, but nothing is showing up. Here are the reviews: {"results":[{"review_text":"good"},{"review_text":"not bad"},{"review_text":"great"}]} Can someone please check m ...

Synchronizing CSS3 Animation Events and Event Listeners in jQuery: A Complete Guide

I've been exploring different ways to utilize CSS3 Animation Events and Event Listeners across browsers for more precise control over CSS3 animations. While I know it's possible, I'm struggling to implement it due to my current limitations d ...

Creating a render function that includes the img.src parameter requires careful thought and consideration

I am currently working on a dilemma where I need to dynamically adjust the height and width of an image in my render() function every time there is a state change. Here is the code snippet: render() { const imageURL = photos[this.state.currentImage]. ...

Guide on creating a toggle effect for a div with querySelector and addEventListener

I utilized the email and password divs provided by Bootstrap. The CSS for the id dropdownlogin includes display: none; in this post, I hope that I have shared adequate information. <script> document.addEventListener('DOMContentLoaded', ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...

Adjust the size of the logo as the user scrolls

Currently, I am implementing a JavaScript feature that allows my logo to shrink when the user scrolls down and grow when they scroll up. To achieve this effect, I am utilizing the jQuery functions addClass and removeClass. However, I have encountered som ...