Using jQuery to show text upon hover using a `for` loop

I'm currently working on a webpage and incorporating a feature where hovering over specific div elements triggers the display of certain text in another div. There are 5 elements that I want to make hoverable and show text upon interaction.

After implementing this feature, I noticed that it wasn't functioning as expected - only the last hoverable div was displaying the text. To troubleshoot this issue, I isolated the elements in question and moved them to a sandbox environment for further testing. Despite my efforts (including using multiple if statements to make it work, but I prefer a cleaner solution), the problem persisted where only the last div would show the text.

Here is a link to the working version with multiple if statements: https://codepen.io/SynergyOfLife/pen/qBNJboR

setInterval(function(){
    var dataArray = ["1","2","3","4","5"]
    var isHovered1 = $(`.${dataArray[0]}`).is(":hover");
    var isHovered2 = $(`.${dataArray[1]}`).is(":hover");
    var isHovered3 = $(`.${dataArray[2]}`).is(":hover");
    var isHovered4 = $(`.${dataArray[3]}`).is(":hover");
    var isHovered5 = $(`.${dataArray[4]}`).is(":hover");


    if (isHovered1) {
        $('p').html("TEST")     
    } else if (isHovered2) {
        $('p').html("TEST")
    }else if (isHovered3) {
        $('p').html("TEST")
    } else if (isHovered4) {
        $('p').html("TEST")
    }else if (isHovered5) {
        $('p').html("TEST")
    } else {
        $('p').html("")
    }
    

}, 300);
div {
    height:100px;
    width: 100px;
    background: blue;
    float: left;
}

.viewer {
    height: 500px;
    width: 500px;
    background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
        <a>Test</a>
    </div>
    <div class="2">
        <a>Test</a>
    </div>
    <div class="3">
        <a>Test</a>
    </div>
    <div class="4">
        <a>Test</a>
    </div>
    <div class="5">
        <a>Test</a>
    </div>
    <div class="viewer">
        <p></p>
    </div>

Here is the version I am striving to refine: https://codepen.io/SynergyOfLife/pen/VwjELME

setInterval(function(){
    var dataArray = ["1","2","3","4","5"]

    var i;
    for (i = 0; i < dataArray.length; i++) {
        var isHovered = $(`.${dataArray[i]}`).is(":hover");
        if (isHovered) {
            $('p').html("TEST")
        } else {
            $('p').html("")
        }

    }


}, 300);
div {
    height:100px;
    width: 100px;
    background: blue;
    float: left;
}

.viewer {
    height: 500px;
    width: 500px;
    background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
        <a>Test</a>
    </div>
    <div class="2">
        <a>Test</a>
    </div>
    <div class="3">
        <a>Test</a>
    </div>
    <div class="4">
        <a>Test</a>
    </div>
    <div class="5">
        <a>Only working div?</a>
    </div>
    <div class="viewer">
        <p></p>
    </div>

In essence, I'm seeking assistance on streamlining the number of if statements in the code.

Answer №1

Utilize the hover() method that requires two functions to handle mouseenter and mouseleave events.

var dataArray = ["1", "2", "3", "4", "5"]
var selectors = '.' + dataArray.join(',');

$(selectors).hover(function() {
  // `this` refers to the element where the event took place
  $('p').html('TEST ' + this.className)
}, function() {
  $('p').empty()
})
div {
  height: 100px;
  width: 100px;
  background: blue;
  float: left;
}

.viewer {
  height: 500px;
  width: 500px;
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
  <a>Test</a>
</div>
<div class="2">
  <a>Test</a>
</div>
<div class="3">
  <a>Test</a>
</div>
<div class="4">
  <a>Test</a>
</div>
<div class="5">
  <a>Test</a>
</div>
<div class="viewer">
  <p></p>
</div>

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 method to provide function parameters without executing the function?

I'm searching for a solution to obtain a function that requires a parameter without actually invoking the function. Example of current malfunctioning code: const _validations = { userID: (req) => check('userID').isString().isUUID(&apo ...

Searching for "unique elements" using AngularJS ng-repeat

I am trying to organize a list by category, but the challenge is that each category input is customized and can be added by any user in the list. My initial attempt involved using ng-repeat to filter out duplicate values (as seen in the code snippet uniqu ...

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

Avoiding duplicate clicks in Onsen UI Navigator.Avoid duplicate clicks in

When a user clicks on an item in my list, they are taken to a details page. However, if the user clicks too quickly, two click events may be fired, leading them to navigate to two different pages consecutively. Is there a way to prevent this issue? Can we ...

The height of the div element is causing issues for the adjacent item in the row

I am facing a styling issue where the height of my avatar image is affecting other inline items located next to it. The images below demonstrate this problem. https://i.sstatic.net/bovge.png https://i.sstatic.net/EsF2R.png As you can see, when I increas ...

The navigation buttons on the Bootstrap carousel will only respond to keyboard commands after the arrow on the

Is there a way to change the default behavior of the bootstrap carousel to allow keyboard navigation without having to click the arrows on the screen first? In my modal, I have a carousel that I want users to be able to navigate using the keyboard arrows ...

Apparent malfunctions in Bower packages

Here are some of the packages available on bower: bootstrap-ui, angular-ui-bootstrap, and angular-ui-bootstrap-bower. It appears that only angular-ui-bootstrap-bower has built js files. Can anyone provide more information on this? ...

Opacity error with jQuery slider specifically affecting Google Chrome browser

My Magento site features a custom-built slider that is both responsive and has unique touch behavior. The desired behavior for the slider is as follows: A three-image slider where the middle image has an opacity of 1.0, while the other two images have an ...

Stopping a parent's event from firing when clicking on child elements without interfering with the child element events

Having read several posts such as this one, I am exploring a method to click on the parent div for it to hide, without hiding when clicking on either the search box or the 'click for event 2' text. I have tried using onclick stop propagation to ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

Encountering an issue when using npm to add a forked repository as a required package

While attempting to install my fork of a repository, I encountered the error message "Can't install github:<repo>: Missing package name." The original repository can be accessed here, but the specific section I am modifying in my fork is located ...

The issue of the Facebook like button not appearing may be due to the sequence in which FB.getLoginStatus() is being

After following the instructions on Facebook's site (http://developers.facebook.com/docs/reference/plugins/like/) to add a basic like button to my website using HTML5, XFBML, and iFrame methods without success, I suspected there may be an issue with m ...

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

How can HTML text be displayed based on certain JavaScript conditions?

By modifying the style of the text, I was able to implement basic functionality for validating correct answers. However, my main query is whether it is feasible to display a specific phrase upon achieving a perfect score. Upon analyzing the provided sample ...

Ensure that the CSS element pseudo-class does not override the styling of its child

Looking to style an anchor element that contains other HTML elements. Here is the basic code structure: HTML: <div class="container" id="sub-menu"> <div class="row" data-bind="foreach: subMenu"> ...

Tips for combining data from various sources in GraphQL

Need some guidance on setting up GraphQL as a beginner. I am facing challenges in efficiently setting up resolvers for my schema, especially when dealing with fields from different backend APIs. type User { name: String address: String dateOfBirth ...

Tips for showcasing information from the tmdb api by leveraging the value or data obtained from a separate api

I am currently working on a project that involves displaying movie data using the tmdb api. I receive the response from my own api which only includes the id of the tmdb movie. Here is an example of the response: [ { "id": 0, "tit ...

An unexpected import token was encountered while using ReactJS and Babel

Every time I attempt to launch my application, an error message pops up that says: (function (exports, require, module, __filename, __dirname) { import { Row } from '../grid' SyntaxError: Unexpected token import I've experimented with vari ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

Once the window width exceeds $(window).width(), the mouseenter function is triggered exponentially

My side menu smoothly folds to the right or left based on the size of the browser window. However, I noticed that upon first reload, the mouseenter and mouseleave events are triggered twice for each action. While this isn't a major issue, it becomes p ...