What methods can be used to pause a jQuery function when hovering and resume it when the mouse leaves?

I'm currently working on a jQuery function that operates on the mousemove event. The goal is to have two images - one main image and one shadow image, with the shadow image reflecting movement based on mouse position. While everything is functioning properly, I am looking for a way to pause the mousemove event when hovering over the main image, only to resume once the mouse is released from the image. Is there a method to achieve this? You can visit the project at this link -

HTML

<div style="width:100%">
<img id="shadow-img" style="position:absolute;"src="./assets/img/slsshadow.jpg"></img>
<img id="center-img" style="position:absolute;left:50%;top:50%;margin-left:-204px;margin-top:-204px" src="./assets/img/slslogo.jpg"></img>
</div>

jQuery

(function() {
    var shadowImg = document.getElementById('shadow-img');
    var centerImg = document.getElementById('center-img');
    document.onmousemove = handleMouseMove;

    function handleMouseMove(event) {
        var center = {
            x : centerImg.getBoundingClientRect().left + 204,
            y : centerImg.getBoundingClientRect().top
        };

        var shadowPos = {
            x : (1.8 * center.x) - event.pageX,
            y : (2.2 * center.y) - event.pageY,
        };

        shadowImg.style.transform = 'translate(' + shadowPos.x + 'px,' + shadowPos.y +'px)';
    };
})();

Answer №1

Below is the code in action (if I understood your request correctly):

(function() {
    var shadowImg = document.getElementById('shadow-img');
    var centerImg = document.getElementById('center-img');
    document.addEventListener("mousemove", handleMouseMove);
    centerImg.addEventListener("mouseenter", function() {
        document.removeEventListener("mousemove", handleMouseMove);
    });
    centerImg.addEventListener("mouseleave", function() {
        document.addEventListener("mousemove", handleMouseMove);
    });
    function handleMouseMove(event) {
        var center = {
            x : centerImg.getBoundingClientRect().left + 204,
            y : centerImg.getBoundingClientRect().top
        };
        console.log(center);
        var shadowPos = {
            x : (1.8 * center.x) - event.pageX,
            y : (2.2 * center.y) - event.pageY,
        };

        shadowImg.style.transform = 'translate(' + shadowPos.x + 'px,' + shadowPos.y +'px)';
    };
})();

No changes were made to the HTML. You can also view it on JSFiddle here: http://jsfiddle.net/wbkdrdpk/2/

Explanation:

To assign events, I used addEventListener like so:

document.addEventListener("mousemove", handleMouseMove);

This achieves the same result as your line of code, but offers the advantage of being able to remove the handler using removeEventListener

I then added two event listeners to the image for removing and re-adding the move handler:

centerImg.addEventListener("mouseenter", function() {
     document.removeEventListener("mousemove", handleMouseMove);
});
centerImg.addEventListener("mouseleave", function() {
     document.addEventListener("mousemove", handleMouseMove);
});

Pretty straightforward.

Edit: I removed any jQuery code as you weren't utilizing jQuery despite tagging your question with it. The tag has been removed as well to avoid confusion ;)

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

apply a visible border to the item that is clicked or selected by utilizing css and vue

I have a list of items that I want to display as image cards with an active blue border when clicked. Only one item can be selected at a time. Below is the code snippet: Template Code <div class="container"> <div v-for="(obj ...

What is the method for accessing an image in JavaScript?

Currently, I am developing a currency converter for a gaming marketplace and I would like the users to be able to generate images using JavaScript. While most of the work is completed, I am facing an issue where the images are not displaying properly and i ...

Adding a listener to an element within a loop

I'm currently exploring a way to add an event listener in my script. Here's the variable I have: var inputs = data.context.find(':input').not(':button'); Following that, I have a FOR loop where I utilize this variable to ap ...

Difficulty reloading after updating input using AngularJS ngTable

I'm encountering an issue where I need to utilize ngTable with TableParams to load and modify a table. For instance, when the page initializes, entering a number in the textbox for the first time displays the appropriate number of rows in the table. ...

"Is there a way to extract text enclosed within HTML tags, such as <div>text</div>, with Selenium using C#

How can I extract the text 'True' from within the HTML tags <div>text</div> using Selenium and C#? <div type='data' id='OfferInCart' style='display:none;'>True</div> I have attempted to retr ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Module.exports causing keyword errors in eslint

Encountering some unusual errors from eslint CI regarding my jest.config.js file. 1:1 error Rule 'no-empty-label' has been replaced by: no-labels no-empty-label 1:1 error Rule 'no-reserved-keys' has been replaced ...

Is it possible to remove Sprites from a three.js scene?

Currently facing an issue where I am trying to update axis labels on a 3D plot by removing the old labels (implemented as sprites) before adding new ones. Unfortunately, I am experiencing difficulties. The previous labels seem to persist in the scene even ...

How can the <animate /> tag be triggered using only CSS and HTML?

Looking for a way to trigger the animation rules of the <animate /> tag using only HTML and CSS. Is there a new standard in HTML and CSS that allows something like input:checked ~ svg animate {enabled:true;} coming up in 2020? Or some other creative ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

Content in Slider Exceeding Container Bounds

After successfully creating a slider using jQuery with the help of some Stack Overflow users, everything was working perfectly. However, when attempting to change the layout of the slider, it somehow broke and now all slides are being pushed out of the con ...

Transmitting HTML5 application settings via URL

I am interested in creating an HTML5 app that utilizes the WebAudio API. This app will allow users to customize certain parameters. Users should be able to 'share' these settings by sending a share URL, which can be clicked by others to view the ...

Use ajax to load the script

Encountering a puzzling issue with a script loading function on my IIS local web server. function loadJs(scriptName) { var name = scriptName.toString(); var myUrl = 'http://192.168.1.149/7.0.9.5/m/js/'; myUrl += name; debugger; ...

What is the best way to ensure that two div elements within a list element fully utilize the available width on a webpage?

I am looking to create a 'settings' div that adjusts its width based on the available space on a page. This could range from 1000px to 600px, and I want the div to always be next to the 'title' div without wrapping onto the next line. F ...

Is it possible to toggle all parent targets in Bootstrap?

When trying to showcase my point, I believe it is best demonstrated by visiting Bootstrap documentation at https://getbootstrap.com/docs/4.0/components/collapse/ and viewing the "multiple targets section." In this section, you will find three buttons: togg ...

Synchronizing Vuetify Carousel with dynamic route parameters

I'm facing an issue where the v-carousel value does not sync correctly with a route parameter using a computed property. Despite waiting for the mounted hook, the carousel seems to emit its own input and disregard the initial value from the route para ...

What are the best practices for utilizing AngularJS's $sanitize service?

Recently, I stumbled upon a tutorial discussing authentication in AngularJS. The tutorial showcased an AuthenticationService that was structured similarly to this: angular.module("auth").factory("AuthenticationService", function ($http, $sanitize) { ...

Guide on bringing in Javascript file into your Ionic/Angular application

Within my Ionic 2 application, I have incorporated three.js along with a PLYLoader extension for three.js (accessible here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/PLYLoader.js) Integrating three.js is straightforward by includi ...

What are some methods to secure my API keys within my React application?

What steps can I take to secure my api keys in my react application? Should I incorporate something with express? My goal is to avoid creating any server-side components to handle the API calls. Currently, my backend is managed by firebase but I also uti ...

Issue with the MUI Autocomplete display in my form

Recently, I started using Material UI and Tailwind CSS for my project. However, I encountered an issue with the Autocomplete component where the input overlaps with the following DatePicker when there is multiple data in the Autocomplete. I have attached a ...