Encountered an issue with adding an event to a class with different IDs

There seems to be a bug in this demo. I am trying to add the same event to the same class but with different IDs. The code looks like this:


var self;
var id;
var result;
var myArray=document.getElementsByClassName("tipDiv");
for (var i=0;i<myArray.length;i++) {
    document.getElementsByClassName("tipDiv")[i].onmouseover=(function(num){
        return function() {            
            $(this).myHoverTip("hoverDiv","");
        }
    })(i);   
    document.getElementsByClassName("tipDiv")[i].onmouseout=(function(num){
        return function() {            
            $(this).cleanHover("hoverDiv");
        }
    })(i);        
}


$.fn.myHoverTip = function(divId, value) 
{
    var div = $("#" + divId); 
    div.css("position", "absolute");
    self = $(this); 
    id = self.attr("id");
    self.hover(function() {
        div.css("display", "block");
        var p = self.position(); 
        var x = p.left + self.width();
        var docWidth = $(document).width();
        if (x > docWidth - div.width() - 20) {
            x = p.left - div.width();
        }
        div.css("left", x);
        div.css("top", p.top);
        function showCustomer(str) {
            var xmlhttp;
            if (str=="") {
                result="";
                return;
            }
            if (window.XMLHttpRequest) {
                xmlhttp=new XMLHttpRequest();
            } else {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function() {
                if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                    result=xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","getbrand.asp?q="+str,true);
            xmlhttp.send();
            div.html(id+result+myArray.length);
        }
        showCustomer(id);
    },
    function() {
        div.css("display", "none");
        div.html("");
    });

 return this;
}

Can someone please help me fix this bug? It is not working as intended. The hover effect does not work on the first mouseover, and the value is incorrect on the second. It only shows the correct value on the third mouseover. When I move to the next DIV, it always shows the last value. Your assistance is greatly appreciated! Apologies for any language errors in my explanation.

Answer №1

Firstly, there is no need to repeatedly call

document.getElementsByClassName("tipDiv")
in the for loop. This information is already stored in myArray, so you can simply use myArray[i].

Alternatively, have you considered using jQuery and the hover function? Check out api.jquery.com/hover. By doing this, you can easily select your class like so:

$(".hoverDiv").hover(...)

Using jQuery and the hover function could simplify things for you.

Another option is to utilize the mouseOver function in jQuery: http://api.jquery.com/mouseover/

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

Automatically populating username and password fields

Is it possible to set up automatic username and password filling on my website for users who have saved their login information in their browser? I want the user to just hit enter to login. Some websites already have this feature enabled, but others requi ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

Click the button to insert a time stamp into the text area

Whenever the id=dodaj_godzine_button is clicked, I would like to add the current time to id=formularz_wpis_tresc (as a string). I attempted to do this using the code below, but it seems to be malfunctioning. $("#dodaj_godzine_button").click(function(){ ...

Adding up rows and columns using HTML

I've designed an HTML table to function as a spreadsheet, with the goal of being able to total up rows and display the sum in a cell labeled "Total." The same calculation should be applied to columns as well, with totals displayed in the last column c ...

A step-by-step guide on revealing a complete div upon selection

Can anyone assist me in showing a div with a form inside it whenever a specific option is selected from a tag? Here is the code I currently have: <script type="text/javascript"> $(function() { $('#contactOptionSelect&apo ...

Issue with Node.js Express function not returning the variable fetched from fs.readFile operation

I am facing an issue with a function in my Node.js application that uses Express. function getMetaInfo(id){ var directory = 'files/' + id; var totalCount = 0; fs.readFile(__dirname + '/' + directory + '/myfile.json&ap ...

Reload the Angular application and navigate to a different state

Introduction In my extensive angular application, there are numerous forms for various items. These forms are associated with action objects that have unique schemaforms. The dropdowns in these forms vary based on the specific action and its parent comp ...

Setting the base URL in Next.js according to an environment variable: a step-by-step guide

I currently have a Strapi backend and Next.js frontend application deployed on DigitalOcean. Within DigitalOcean, I have configured an environment variable for the frontend: API_URL = ${APP_URL}/api To generate the base URL, I retrieve this variable using ...

Unlocking the potential of input values in Angular.jsDiscovering the secret to

I'm currently experimenting with the angular date picker directive. My goal is to retrieve the entered date value from the date picker and log it to the console. However, all of my attempts so far have been unsuccessful. Here's a snippet of my c ...

Update the 'checked' attribute of a radio button when the form is submitted

How do I dynamically change the content of an HTML table based on which radio button a user selects using jQuery? For example, when the page loads, I want the United Kingdom radio button to be checked and the table content to display as 'blue'. I ...

Google Chrome extension with Autofocus functionality

I developed a user-friendly Chrome extension that allows users to search using a simple form. Upon opening the extension, I noticed that there is no default focus on the form, requiring an additional click from the user. The intended behavior is for the ...

Looking to streamline your webpack configuration in vue.config.js? Utilize webpack-chain for efficient setup. And, wondering how to leverage the speed-measure-webpack

Below is the setup in my vue-cli3 configuration file: vue.config.js: const path = require('path') const CompressionWebpackPlugin = require('compression-webpack-plugin') const SpeedMeasurePlugin = require("speed-measure-webpack-plugin" ...

What could be the reason for the absence of the HTTP response in the network tab of the Chrome debugger?

After utilizing Postman to test my web service, I was able to find the WS's response in the http response body. However, when I made a call using ajax in my web application, I encountered an issue where I could no longer locate the response. The tab ...

Changing the ng-include and ng-controller dynamically in your AngularJS project

I'm working on a section of my webpage that features multiple tabs, each requiring a partial and controller to function properly. My goal is to dynamically switch the ng-include and ng-controller based on the currently selected tab. One challenge I&a ...

Why do I have to press the button twice for it to actually work?

I am new to programming and I want to create something that has 3 buttons to control the display of 3 hidden images respectively. When I click the first button, the image appears immediately, but I have to click it twice to show the second image. Can anyon ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

Having difficulty connecting images or photos to CodePen

I've been attempting to connect images and sound files to my CodePen project using a Dropbox shared link. <div class="container"> <div class="row second-line"> <div class="col-12"> <div d ...

Consecutive POST requests in Angular 4

Can you assist me with making sequential (synchronous) http POST calls that wait for the response from each call? generateDoc(project, Item, language, isDOCXFormat) : Observable<any> { return this.http.post(this.sessionStorageService.retriev ...

The Shopify Pixel Extension has encountered an issue - error code 1

Looking to develop a web pixel extension for my Shopify app, I followed the official guide: While building the app, encountered this error: extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify ...

EdgeDriver with Selenium and Java can be interrupted by a modal window dialog box, causing the test script to pause its execution

I am in the process of creating a test script for our web application to test the upload functionality of a profile picture using Microsoft Edge and EdgeDriver. However, I am facing an issue where the script stops running completely after initiating the cl ...