Managing touch devices and animations when hovering

Is there a way to remove or prevent all hover effects on a touch device? I've tried various scripts, but none seem to work for me. How can I test it with dev tools? I attempted this script but received an error: Cannot read property 'addEventListener' of null. Interestingly, it works here codepen. Could the error be because the dom tree has not loaded yet?

<html class="hover-active">

$(window).on('load', function() {

        if (!('addEventListener' in window)) {
            return;
        }

        var htmlElement = document.querySelector('html');

        function touchStart() {
            htmlElement.classList.remove('hover-active');

            htmlElement.removeEventListener('touchstart', touchStart);
        }

        htmlElement.addEventListener('touchstart', touchStart);
    });

I also tried this method:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){}

In addition, I experimented with using modernizr, which only seems to work for selectors inside html.touch and html.no-touch.

function is_touch_device() {
 return 'ontouchstart' in window        // works on most browsers 
  || navigator.maxTouchPoints;       // works on IE10/11 and Surface
};

if ( is_touch_device() ) {
  $('html').addClass('touch')
} else {
  $('html').addClass('no-touch')
} 


html.touch .hover-me:hover {
   pointer-events: none !important;
   cursor: pointer;

}
html.touch a:hover {
   pointer-events: none !important;
   cursor: pointer;
}

/* FOR THE DESKTOP, SET THE HOVER STATE */
html.no-touch .hover-me:hover {
   width: auto;
   color:blue;
   background:green;
}
html.no-touch a:hover {
   width: auto;
   color:blue;
   background:green;
}

However, my goal is to remove all :hover selectors. The * selector does not work for this purpose. It seems like I'm still struggling to make it work.

  .hover-me:hover {
     background: yellow;
 }
html.touch .hover-me:hover {
   pointer-events: none !important;
   cursor: pointer;

}

Answer №1

If you want to eliminate all hover effects on touch screen devices, one approach is to utilize CSS Media Queries to ensure that the device has full support for hover actions before implementing any :hover styles. This can be achieved by encapsulating the styles within @media (hover: hover).

@media (hover: hover){
  .hover-me:hover {
     background: yellow;
 }
}

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

Transformation of visuals with alteration of status

I am attempting to change the image of a door from closed to open when the status changes in my home automation dashboard. I need help with this task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&qu ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

Changing the format of PHP SQL results from vertical to horizontal

Is there a way to convert the vertical table generated by the following code into a horizontal one with stylish formatting? Additionally, is it possible to display certain columns in a popup window based on query parameters using jQuery or CSS? <html&g ...

Adjust the position of the icon in the Mui DatePicker widget

How can I customize the mui DatePicker? I successfully changed the icon, but now I need to adjust its position as well. Instead of being at the end of the text, I want the icon to be at the beginning. Here is my code: <ThemeProvider theme={calendarThem ...

Launching a bootstrap modal within another modal

I am facing a minor issue with two modal popups on my website. The first modal is for the sign-in form and the second one is for the forgot password form. Whenever someone clicks on the "forgot password" option, the current modal closes and the forgot pas ...

Using jQuery to parse JSON transforms an array into a hash object

I recently encountered an issue with a string that I needed to convert into a JSON object. The string looked like this: string = '{ "key": [ { "foo": "bar" } ] }'; To convert the string, I used: json = $.parseJSON(string); However, after co ...

What is the alternative to jQuery.submit now that it has been deprecated in version 3.3?

After reviewing the source code, you will find: /** * Attach an event handler to the "submit" JavaScript event, or trigger that event on an element. * * @param handler The function to be executed each time the event is triggered. * @see {@link https:/ ...

Safari shows a contrasting outcome

Having an issue with compatibility in the safari browser You can check out the site here: The problem lies with the text inside the image, I want it to display properly like it does in Chrome. Here is the desired result for Safari as well. Below is the ...

The function `jQuery .html('<img>')` is not functional in Firefox and Opera browsers

This particular code snippet jq("#description" + tourId).html('<b>Opis: </b> '+ data); has been tested and functions correctly in Internet Explorer, Firefox, and Opera. However, when it comes to this specific piece of code jq("#i ...

Setting a div's background using JavaScript works flawlessly on jsfiddle.net, but encounters issues when implemented in actual code

contains the files you need. For reference, here is the link to the code on I have attempted to remove all unnecessary elements from the actual project, but it has not made a difference. document.getElementById("image").style.backgroundImage = "url(" + d ...

When the text is long, it does not extend all the way to the right

I am working on designing a login page and have created an input text field for the user's email address. However, I have noticed that when the email address is long, there is some space left at the end of the border (I suspect it may be due to paddin ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

When using select2 with AJAX, ensure that the previous response is cleared when the field

Learn how to implement select2 $("#select").select2({ ajax: { url: "/getcity", dataType: 'json', type: 'post', delay: 250, allowClear: false, minimumInputLength: 3, cache: true } }); Every time I focus, ...

Turn off background sound on mobile devices

I have a question about the script I'm using to play a background audio theme on my website - is there a way to prevent it from automatically playing on mobile devices? $(document).ready(function() { var audioElement = document.createElement ...

Utilizing jQuery Autocomplete to access JSON data via an API

My understanding of jQuery autocomplete is a bit limited, so I'm hoping for some guidance on how to achieve my task. I currently have the following URL: http://localhost/contactApi.do?mobile=614321 This URL allows for inputting either a complete or ...

Prevent the appearance of a scrollbar on a fixed-position popup element

Whenever I click on a button, a Sidebar opens up and fills the entire screen due to its position being set to fixed. Here's how it looks with TailwindCSS: return ( <div className="fixed z-40 flex left-0 top-0 h-screen w-screen"> ...

If the element contains a specific class, then remove that class and apply a new

Encountering an issue here. I have 4 HTML elements structured like this: <!-- Light Color Scheme - Header False and Show Faces True --> <div class="fb-like-box h-f_dsf-t visible" data-href="http://www.facebook.com/pages/Alpine-Adaptiv ...

How to arrange table data in Angular based on th values?

I need to organize data in a table using <th> tags for alignment purposes. Currently, I am utilizing the ng-zorro table, but standard HTML tags can also be used. The data obtained from the server (via C# web API) is structured like this: [ { ...

Can parameters be passed in an ajax request with a dynamic parameter name in asp.net?

Can someone help me with an issue I am facing with ajax requests? I have a post ajax request in asp.net where I pass parameters. When I change the parameter name in the code behind (aspx.cs), the request fails to post. However, when I tried the same with M ...

The background image will expand to fill any available space

I'm currently working on rendering divs with a background image CSS property. The images have fixed sizes, and I want to display them in a grid layout. However, the divs with background images stretch when there is extra space available, which is not ...