How can I prevent mouse movement hover effects from activating in a media query?

I have implemented a custom image hover effect for links in my text using mousemove. However, I want to disable this feature when a specific media query is reached and have the images simply serve as clickable links without the hover effect. I attempted to use the off() method to achieve this, but it doesn't seem to be working. Can anyone suggest a better solution? Thanks.

$(document).ready(function() {
    $('.text-hover').mousemove(function(e) {
        $img = $("#" + $(this).data('image-id'))
        $img.stop(1, 1).show().fadeIn("slow");
        $img.offset({
            top: e.pageY + 20,
            left: e.pageX + 10
        });
    }).mouseleave(function() {
        $img = $("#" + $(this).data('image-id'))
        $img.hide();
    });
    window.addEventListener('resize', function(){
        if(window.innerWidth > 568){
            $('html').off('mousemove');
        }
    });
});

Answer №1

If you are trying to remove an event listener using .off(), you need to change the way it was added. As per the documentation, .off() only removes events attached with .on().

The .off() method removes event handlers that were attached with .on().

To test this, resize your browser window and then make it large again. The event should be removed.

$(document).ready(function() {
    $('.text-hover').on('mousemove', function(e) { // use .on()
        $img = $("#" + $(this).data('image-id'))
        $img.stop(1, 1).show().fadeIn("slow");
        $img.offset({
            top: e.pageY + 20,
            left: e.pageX + 10
        });
    }).mouseleave(function() {
        $img = $("#" + $(this).data('image-id'))
        $img.hide();
    });
    window.addEventListener('resize', function(){
        console.log("resize");
        console.log(window.innerWidth);
        if(window.innerWidth > 568){
            $('.text-hover').off('mousemove'); // Remove it from the element you attached it too
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-hover" data-image-id="1">
Erat diam clita exerci elitr eos enim eros autem consetetur invidunt ea clita consetetur labore ea magna et consetetur ipsum justo dolor dolor at nonumy rebum eros in eirmod qui dolor odio tincidunt justo lorem labore autem ipsum aliquam invidunt est volutpat amet takimata magna ea dolor duo dolor dolor justo ipsum clita kasd nonumy diam voluptua esse lorem kasd lorem et lorem at no lorem sed sadipscing dolore diam nonumy erat sed sed sadipscing gubergren sit nonumy diam diam dolore sea dolore sed sit dolore quod nostrud erat augue sea et erat amet magna ut dolore ipsum duis dolore velit nostrud in facilisis vero diam lorem lorem qui in minim suscipit gubergren aliquyam magna amet no clita et id lorem eu autem diam erat minim diam accusam diam in labore sadipscing vulputate nibh molestie accusam ipsum dolores dolore dolor dolor esse sea nam invidunt dignissim clita in rebum luptatum elitr justo diam diam gubergren elitr kasd et labore kasd clita aliquip sed diam sed justo ea lorem augue no ut elitr zzril aliquyam ea dolor magna elitr hendrerit in justo sed takimata sed sit rebum amet sit ipsum sadipscing kasd feugiat praesent stet dolore sea voluptua aliquyam amet amet odio consectetuer vero lobortis illum amet nonumy nihil no no velit justo at in sadipscing et id gubergren clita voluptua invidunt consequat amet est lorem laoreet no clita lorem laoreet takimata nulla et sed tempor est et accusam lorem labore voluptua ut elitr consetetur sanctus et facilisi voluptua consetetur gubergren praesent diam lorem tincidunt stet voluptua ipsum esse ut no at voluptua ea invidunt amet in consetetur et ipsum odio in eos ut sed vel sit dolor dolor ipsum mazim rebum et ut eirmod et feugiat sanctus invidunt erat duis justo imperdiet et diam feugait et suscipit sanctus consetetur rebum dolore tincidunt eos tation vulputate at consetetur nostrud eirmod clita ea molestie diam stet consetetur kasd eros quis et ipsum iusto takimata lorem eirmod sit amet accusam sit vulputate tempor ea invidunt sed dolores amet no sed dolore magna diam sanctus veniam eos et amet ipsum sanctus dolor amet lorem sanctus amet nonumy quis nostrud vero qui ut liber elitr labore ipsum eos volutpat ut ipsum consetetur nonumy sit cum dolor aliquyam diam nonumy dolor takimata id esse accusam praesent et consequat amet diam dolore et dolor feugiat at accusam nonumy vero sed sed eirmod sea in iriure wisi accusam voluptua dolores dolor feugait dolor at est amet augue soluta erat dolor consectetuer eirmod ut volutpat ipsum blandit sed dolor sit duis rebum aliquyam facilisis kasd vulputate clita dolor velit duo ipsum lorem amet dolor et elit no at tempor ea dolor ipsum elitr elitr elitr elitr ipsum facilisis invidunt sadipscing eirmod est iusto et vel lorem eos amet invidunt invidunt elitr ipsum nonumy dolor aliquyam in eu wisi erat invidunt nonumy sit ut duis aliquam consetetur sanctus magna molestie justo iusto est duis amet amet minim ea commodo sadipscing et dolore ad accusam duo justo lorem ipsum nonumy amet
</div>
<img id="1" src="https://avatars3.githubusercontent.com/u/12504876?v=4" style="width:50px;height:50px">

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

Page elements subtly move when reloading in Chrome

I am experiencing an issue with a div that has left and top offsets randomly selected from an array of values upon page load. Most of the time, it works fine. However, occasionally, upon refreshing the page, the window scrolls down slightly, revealing the ...

Is there a way to display a div element just once in AngularJS?

I only want to print the div once and prevent it from printing again. $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', '_blank', 'width=300, ...

In what ways can you shut down an electron application using JavaScript?

My Electron app is running an express server. Here is the main.js code: const electron = require("electron"), app = electron.app, BrowserWindow = electron.BrowserWindow; let mainWindow; function createWindow () { ma ...

Creating a conditional statement within an array.map loop in Next.js

User Interface after Processing After retrieving this dataset const array = [1,2,3,4,5,6,7,8] I need to determine if the index of the array is a multiple of 5. If the loop is on index 0, 5, 10 and so on, it should display this HTML <div class="s ...

Supervising ongoing asynchronous tasks within Node.js's promise-based ecosystem

In my Node.js application, I have created a reliable robot program that continuously sends requests to an API. I have taken precautions by handling errors and setting timeouts for promises in order to prevent any issues from occurring. Now, I am looking t ...

Error Message "Alexa.create is not a valid function" encountered while using the Alexa HTML Web API on the Echo Show 10

Here is the HTML code for my custom Alexa Skill. <head> <script src="https://cdn.myalexaskills.com/latest/alexa-html.js"> </script> </head> <body> var alexaClient; Alexa.create({version: '1.0'}) .t ...

Using JQuery to Refresh a Div and Trigger an API Call with a Click Event

Currently, I am working on developing a web application that generates random quotes dynamically. Using JQuery, I can successfully make an API call and retrieve JSON data to display a quote. To allow users to fetch new quotes with the click of a button, I ...

watchWebpack is compiling all the files

As per the webpack documentation on watching files webpack can keep an eye on files and recompile them whenever there are changes. My understanding is that this implies webpack will only compile the files that have been modified. I have a configuratio ...

Tips for providing support to a website without an internet connection

I am in the process of creating a sales platform for a grocery store that utilizes PHP/MySQL. I have come across some websites that are able to fully reload and function even without internet access. For instance, when I initially visited abc.com, everyth ...

problem with the visibility of elements in my HTML CSS project

How do I prevent background images from showing when hovering over squares to reveal visible images using CSS? h1 { text-align: center; } .floating-box { float: left; border: 1px solid black; width: 300px; height: 300px; margin: 0px; } div ...

When attempting to import vue.js within a JavaScript file in a Django application, an error of 'Uncaught SyntaxError: Cannot use import statement outside a module' is encountered

Currently, I am delving into incorporating vue.js into a live django project and have come across a stumbling block. After setting up npm in the venv environment and installing the vue package, my next step is to create a Vue object within a js file using ...

Leveraging setter methods within knockoutjs bindings allows for efficient data manipulation

As the day comes to a close, my mind is winding down for the night. I've been diving into the world of setters when dynamically binding to Html elements and trying to wrap my head around it. While I have read through several examples, these URLs below ...

How can we include identical item names within a single JavaScript object?

My attempt at achieving the desired result involves creating an object like this: var obj = {id: id, items: "asdf", items: "sdff", test: varTest}; However, I face a challenge where I need to dynamically add two elements with the same name 'items&apo ...

Updating a child component in React while applying a filter to the parent component

Although I've come across this question before, I'm struggling to comprehend it within my specific scenario. I'm currently using a search bar to filter the data, which is functioning properly. However, the image is not updating. The URL bei ...

Having issues with AJAX and .change() function not functioning correctly?

I am working on two drop-down menus. The first menu displays the provinces in the country, and when a province is selected, the second menu should show the districts within that province. The following code is for displaying the provinces: $(document).re ...

Implementing MUI createTheme within Next.js

After switching from material-UI version 4 to version 5.5.0 in my project, I encountered issues with createTheme. The colors and settings from the palette are not being applied as expected. Current versions: next: 11.0.0 react: 17.0.2 mui : 5.5.0 theme. ...

Subsequent $http requests become trapped in a pending state and eventually fail with a NodeJS server

I encountered a strange issue with Angular and Node that I can't seem to find a solution for. In my Angular controller, I have a function that fetches data initially and stores it in $scope. This function also allows the controller to make a POST req ...

What should be placed in the viewRef: MapViewNativeComponentType parameter when utilizing React Native Maps in the current.fitToSuppliedMarkers function?

useEffect(() => { if(!origin || !destination) return; mapRef.current.fitToSuppliedMarkers(["origin", "destination"], { edgePadding: { top: 50, right: 50, bottom: 50, left: 50} }) }, [origin, destination]); I'm currently in t ...

unable to retrieve element values using class names

I have created multiple h1 elements with the same class names listed below. <h1 class="h1">One</h1> <h1 class="h1">Two</h1> <h1 class="h1">Three</h1> <h1 class="h1">Four</h1> I have also added a button that ...

Tips for utilizing the @Input directive within the <router-outlet></router-outlet> component

I am new to Angular 4 and recently discovered that in Angular, data can be passed from a parent component to a child component using @Input like this: <child [dataToPass]="test"></child> My question is, how can I achieve the same functionalit ...