"jQuery enables hover effects to be applied to elements that are not directly related

I'm attempting to achieve an effect where an element will show or hide when I hover over a completely different element.

Currently, my approach involves using lists and indexes so that the nth item in list 2 changes when the nth item in list 1 is hovered over. This method would provide a general solution for multiple objects rather than individually pairing elements and writing jQuery rules for each one. While I've looked at other discussions on this topic, none seem to offer a universal solution.

Below is a sample of code I've been experimenting with:

I am relatively new to jQuery, so thank you for your understanding and patience as I navigate through this learning process.

<!doctype html>
<html>
    <head>
        <title>addClass demo</title>
<style>
.disappear { display: none }
</style>
<script src="jquery-1.10.2.min.js"></script>
    </head>
    <body>
        <ul>
            <li class = "one">Hello</li>
            <li class = "one">and</li>
            <li class = "one">Goodbye</li>
        </ul>
        <ul>
            <li class = "two">Hello</li>
            <li class = "two">and</li>
            <li class = "two">Goodbye</li>
        </ul>
<script>
$( "li one" ).on('mouseenter', function() {
 var indx = $(this).eq();
 $("li two").eq(indx).addClass("disapear");
}); 
$( "li" ).on('mouseleave', function() {
 $(this).removeClass("disappear");
}); 
</script>
    </body>
</html>

Answer №1

Error

  1. Your error is in the spelling of the class. It should be disappear instead of disapear
  2. Replace $( "li one" ) with $("li.one") and $( "li two" ) with $("li.two")
  3. Opt for using index() over eq()
  4. Consider using .hover() method

Solution

$("li.one").hover(function () {
    var indx = $(this).index();
    $("li.two").eq(indx).addClass("disappear");
}, function () {
    var indx = $(this).index();
    $("li.two").eq(indx).removeClass("disappear");
});

DEMO

Answer №2

eq() does not provide the index of the current element, as detailed in http://api.jquery.com/eq/. Its behavior is undefined without a parameter.

To find the index, use index() like so:

var indx = $(this).index();
$("li.two").eq(indx).addClass("disappear");

Note that there was a typo in your original code: it should be disappear instead of disapear.

Also, make sure to use "li.one" and "li.two" as selectors for elements with those classes, not "li one" - remember the dot denotes a class selector.

You may want to consider adding the class to the <ul> instead and selecting using "ul.one li" instead.

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

Display a Bootstrap input button group addon, where the first button has rounded corners only after the second button has been hidden

I am working on a button group and need to hide the second button dynamically. However, I am facing an issue where the first button has a 90° border. How can I adjust the code below to display button 1 with a rounded border? If I decide to hide "button ...

Steps to eliminate the x icon from the text box that appears automatically in Internet Explorer

I'm currently working with a UI5 text box that includes a built-in option for clearing the text using a 'X' button. However, I've noticed that in Internet Explorer, an additional default cross mark is being added alongside the UI5 cros ...

Steps for populating a table with data from a JSON array

I am currently facing a challenge in populating an HTML table with data retrieved from a two-dimensional array. The information is being fetched through an $.ajax script after executing a php/MySQL query. Despite successfully parsing the data in the succes ...

Troubleshooting Autocomplete User Interface Problems

I am currently working on a website user interface and I have encountered an issue specifically in IE7. When searching for a company, the display is not showing up correctly, as demonstrated in the image below. This problem only occurs in IE7, it works fi ...

Ways to automatically refresh a page without losing the current content within a div every minute

Currently, I am developing a food status tracking system that assigns a unique order number to each order. Upon loading the page, I make an AJAX call to retrieve the current status of the order. This information is then added to a div. However, I want any ...

Cast your vote with Mysql, Jquery, and Php!

My attempt at creating a voting system using PHP, MySQL, and jQuery seems to be functioning properly on the front-end. However, I am facing an issue where it does not add data to the database on the back-end. Any assistance or suggestions on this matter wo ...

Converting JavaScript strings into nested arrays

Currently, I am developing my own bi-directional DOM binder to connect input fields to JSON data as a way to enhance my understanding and skills. I have chosen not to use frameworks like Ember, Angular, or KnockoutJS for this project. One challenge I am fa ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Challenges in Maintaining the Integrity of HTML5 Semantic Tags (article, footer, header)

When it comes to the new layout tags in HTML5, how effectively do they degrade? What risks are involved in using them? (I'm excluding <video>-- as I've come across specific fallback code for it). For instance, consider the following snippe ...

Is it possible to personalize CSS properties using PHP sessions?

Currently, I am a beginner in PHP and enrolled in a technical school class to learn more about it. Our latest assignment involves using sessions to modify four CSS properties: body background-color, a:link color, a:hover color, and h1 color. The task inclu ...

changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a <div id="po" style="display:none;">some html</div> element. The first time I click the link, the div displays properly. However, after tha ...

Centralized and secure masthead

Currently, I am focusing on showcasing my portfolio at www.bbellmedia.com/mywork The specific requirement I have is to center the text 'Bryan Bell' and ensure that it remains fixed even when the user scrolls. Can anyone suggest the most effecti ...

Storing user-provided image files in Laravel: A comprehensive guide

I am facing an issue with a file insert box in my HTML file. The code looks like this: <input id="image" type="file" name="image" value="{{ old('image') }}" accept="image/gif, image/jpeg, image/png& ...

Global jQuery variables are unexpectedly coming back as "undefined" despite being declared globally

I need to save a value from a JSON object in a global variable for future use in my code. Despite trying to declare the country variable as global, it seems like it doesn't actually work. $.getJSON(reverseGeoRequestURL, function(reverseGeoResult){ ...

Tips for creating a functional Submit button in HTML

How can I ensure that the submit button sends the necessary information to my email address when clicked (e.g. [email protected])? If PHP is required, please provide the code so I can easily integrate it into my project. Thank you! <div id="forms ...

What is the best way to ensure grid element takes up 100% of the available height within a flex column

I am working with this HTML structure: https://i.stack.imgur.com/fy5Yz.png My goal is to have the .SceneWithHistory-Container take up 100% of the available height in its parent element. Below is my CSS code: .Module-Container margin-top: 120px; displ ...

Utilizing a Json.Net object within an Ajax request

Is there a way to pass a .Net object in an Ajax call using the Json.Net javascript library instead of json2.js? You can find more information on passing complex types via Ajax calls at this link: I am familiar with how to serialize and deserialize object ...

Footer positioned correctly with relative DIV

I find myself in a state of complete confusion. Coding is not exactly my forte, so I suspect I have made a significant error somewhere that is causing the following issue: My goal is to create a sticky footer. The footer does indeed stick to the bottom of ...

What is the process to determine which section of the image is shown when I hover over it?

I have implemented colorbox for popups on my website located at in the "OUR PORTFOLIO" section. I customized the default images for previous, next, and close buttons, but when I hover over them, they display the wrong parts of the image. I'm unable t ...

Implementing a color change for icons in React upon onClick event

export default function Post({post}) { const [like,setLike] = useState(post.like) const [islike,setIslike] = useState(false) const handler=()=>{ setLike(islike? like-1:like+1 ) setIslike(!islike) } return ( <> <div classNam ...