Function triggered by onmouseover continues to trigger repeatedly upon mouse hover

I have a function that activates when the mouse hovers over a div.

Inside the div, there is a link that spans 100% of its height and width. This link contains an image that the function moves when the grandparent (the div) is hovered over.

The function moves the image to the right before returning it to the center.

When I hover over the div, the function triggers but only moves the image by 5px (one iteration of the function), continuing to move it 5px as I move the mouse around - essentially not looping properly and only executing once per hover.

<div onmouseover="jotArrow(this);" class="latest-entry latest-entry-third" id="news-link-home">

<a class="home-square-link" href="hello.php">Reviews<br/><img src="<?php echo $config['file_path']; ?>/images/squares-arrow.png" width="60px"/></a>

</div>

JS:

var arrowPos = 0;
var Arrow;

function jotArrow(arrow)
{
    Arrow = arrow.getElementsByTagName('img')[0];

    if (arrowPos < 50) {
        arrowPos = arrowPos + 5;
        Arrow.style.left = arrowPos + 'px';
        setTimeout(jotArrow, 10);
    } else {
        jotArrowBack(arrow)
    }
}

function jotArrowBack(arrow)
{
    if (arrowPos > 0) {
        arrowPos = arrowPos - 5;
        Arrow.style.left = arrowPos + 'px';
        setTimeout(jotArrowBack, 10);
    }
}

To verify the code's accuracy, I made a slight modification so that it moves an image in a different div (hovering over div1 makes the image in div2 move), and it worked correctly.

My assumption is that the issue may stem from the image being nested inside the div and the mouse hovering over multiple elements. However, I don't see why this would be problematic since the function should execute its entire task on the initial hover without concerning itself with onmouseout events.

I've attempted adding the onmouseover attribute to each of the three elements (div, a, img) individually and simultaneously - yet encountered the same issue.

Answer №1

It seems like there are a couple of issues with your code. Firstly, you're encountering multiple mouseover events which are causing confusion within the code's functionality. Secondly, the jotArrow function fetches the Arrow element each time it is called, but on the second call, it fails to find it because the parameter is not passed in the setTimeout function. Additionally, when switching the code to move a different element, you may be using something like document.getElementById('blah') which selects the same element repeatedly.

An alternative solution would involve creating a helper function called initArrow, similar to the following example:

function initArrow(arrow)
{
    if (arrowPos == 0) {
        Arrow = arrow.getElementsByTagName('img')[0];
        jotArrow();
    }
}

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

Setting up a new package through JPSM installation

I utilize jspm in my web application. My goal is to install the npm:angular2 package without needing to set it up in the config.js file. Instead of loading the angular2 module via jspm, I manually added the angular2 library like this: <script src="jspm ...

Executing a setTimeout function within an Ajax call in a loop

I am attempting to execute a function after a delay of 1 second, but the function is triggered within an ajax call inside a foreach loop. Code: let index = 1; portals.forEach(portal => { setTimeout(() => { $.ajax({ type: "PO ...

The Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

What is causing the ReferenceError message stating that db is not defined to appear in my code

I am facing an issue with connecting axios to the DB. It is a MYSQL server, and although I can retrieve data using app.get in the server file, the connection does not persist when using express DB connection. Strangely, everything works fine in postman and ...

Learn the magic of jQuery: toggling table row visibility effortlessly!

I am currently working on a PHP application using Zend Framework that includes a table with a large number of rows. Most users interact with either the first or second row about 99.9% of the time. Only around 0.1% of users need to revisit previous rows f ...

Navigating CSV-derived JSON data in Flask and Javascript: Best Practices

My current goal is to read a CSV file on the backend using Python/Flask and then display its data as an HTML table with Javascript. I have simplified my task to just displaying JSON values passed from Python in the browser console, which will help me build ...

creating a Vuejs button function that will add together two given numbers

Help needed with VueJs code to display the sum of two numbers. Seeking assistance in developing a feature that calculates the sum only when the user clicks a button. Any guidance would be greatly appreciated! <!DOCTYPE html> <html lang="en"> ...

I am encountering an issue where the jQuery load() function is not successfully loading my Django view within

After setting up my HTML, I wanted to include my Django view in the "radio2" div. To achieve this, I utilized the JQuery function Load(). However, I encountered an issue where it kept returning a 404 error with the get request "http://127.0.0.1:8000/post/a ...

Struggling to set a global variable path in Node.js using the accessSync function in

Having an issue with the Sync function in FS core of nodejs. Consider a nodejs file containing the following code: var y; fs.accessSync("real_exixs_path", fs.R_OK | fs.W_OK, function(err) { if (err) { console.log("File error!"); } else { y = " ...

AngularJS button click not redirecting properly with $location.path

When I click a button in my HTML file named `my.html`, I want to redirect the user to `about.html`. However, when I try using `$location.path("\about")` inside the controller, nothing happens and only my current page is displayed without loading `abou ...

Exploring Angular 4: Iterating Over Observables to Fetch Data into a Fresh Array

Context Currently, I am in the process of developing a find feature for a chat application. In this setup, each set of messages is identified by an index. The goal of the `find()` function is to retrieve each message collection reference from the `message ...

What is the best way to create a dropdown menu that smoothly slides in from the bottom of the screen?

Is it possible to create dropdown menus in the navigation bar that slide in from the bottom with a smooth transition effect, similar to this example: Although I am working on building my own template, so my code may differ from the original theme. Here is ...

Is there a way to transfer ngClass logic from the template to the TypeScript file in Angular?

I am implementing dropdown filters for user selection in my Angular application. The logic for adding classes with ngClass is present in the template: <div [ngClass]="i > 2 && 'array-design'"> How can I transfer this ...

Tips for incorporating an HTML file using ng-include in double curly brace syntax {{ }}

Here is the code snippet I am working with: <div ng-repeat="pTabs in child.productTabs" ng-click="toggleProductTab($index)" ng-if="productTabIsActive(pTabs, $index)"> <div ng-repeat="specs in pTab.additionalSpecs"> <p>{{spec ...

Switching Vue.js from the standalone build to the runtime-only build midway through a project?

Opted for the runtime-only version of Vue.js for a new project. I came across in the documentation that to switch to the standalone version, one must include an alias in webpack like this: resolve: { alias: { 'vue$': 'vue/dist/vue.js& ...

What is the reason behind a number having its final two digits transformed into zeros?

Query Hello, I was coding my discord bot and storing user IDs in a database. I plan to use these IDs to ping or assign roles to users. Issue However, I encountered a problem where the IDs in the database are being altered. For example, from 5336929053871 ...

Selecting the checkbox will activate the POST endpoint

I am working on a nodejs/express app and looking for a way to update my database using a POST route when a checkbox is clicked. The challenge I am facing is that I want to avoid using a submit button or jQuery. I am currently using a Bootstrap4 checkbox ...

How can one display blog data (stored as a PDF) from a database alongside other different results (stored as

I have successfully displayed a PDF file from my database as a blob using the header("Content-type:application/pdf") method. Now, I am looking to also display some additional string results along with this PDF file. Is it feasible to achieve this while d ...

Establishing communication from a node.js application to an Apache server with version 2.2

Each time I call the function dorequest during a request to my node server, I encounter an issue with requests to a webpage hosted on apache2.2.21. While most of the requests are successful, I am getting an error ECONNRESET on a few of them, and I am uns ...

Setting the date in a datetimepicker using the model

I've encountered an issue while trying to utilize the angular date time picker. It seems that when I load data from the model, the picker does not bind the value correctly. If I manually set the value to a date, it works fine. However, when the data ...