Use JavaScript to change the CSS pseudo-class from :hover to :active for touch devices

Looking to eliminate hover effects on touch devices? While it's recommended to use a hover class for hover effects, instead of the hover pseudo-class, for easier removal later on, it can be a challenge if your site is already coded. However, there's a clever solution to target all :hover pseudo-classes in CSS and replace them with :active. The :active pseudo-class should work effectively for your needs, but you may encounter some issues with the JavaScript code. If there are errors, they may be difficult to spot.

function touch() {
  if ('ontouchstart' in document.documentElement) {
    var sheet = document.getElementById("#pagestyle");
    if (sheet.cssRules) {
      for (var i = 0; i < sheet.cssRules.length; i++) {
        var rule = sheet.cssRules[i];
        if (rule.selectorText) {
          rule.selectorText = rule.selectorText.replace(':hover', ':active');
        }
      }
    }
  }
}
.test:hover {}
<link id="pagestyle" rel="stylesheet" href="css/style.css">

Answer №1

Why spend time writing extensive code in JS when you can simply add a rule to your stylesheet?

.test:hover,
.test:active {
}

I'm unsure why the :active rule isn't being added as shown above. If you only want to apply CSS for :hover and non-hover devices, you can utilize a media query like this:

@media (hover: hover) {
  .test:hover { }
}
@media (hover: none) {
  .test:active { }
}

Another option is:

/* the device does not include any pointing device. */
@media (any-pointer: none) {
    /* ... */
}

For further information, you can refer to this source

I hope you find this helpful. However, I personally believe that the approach demonstrated in the first code example is much more effective than adding additional complexity.

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

The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with: $(document).ready(function(){ $(".subscriptions").click(function (){ if($(".pollSlider").css("margin-right") == "-200px"){ $('.pollSlider').animate({"margin-right": '+ ...

The absence of PHP GET variable being set

I am encountering an issue with my registration php class. It is designed to display a form and upon clicking the registration button, it triggers a function in a login javascript file. This JavaScript file utilizes ajax to send data to an index.php file. ...

Eliminating the need for horizontal scrolling in the window causes a change in the height of an internal DIV element

Check out this snippet of code, a simplified version of a larger piece: html, body { margin: 0 !important; padding: 0 !important; /* overflow-x: hidden; /* uncomment this line */ } .app { position: relative; width: 100%; text-align: center !important; } ...

An issue arises when attempting to utilize the 'push()' method to append a string to a JSON array

I am looking to append strings to my JSON file structure shown below: { "items": [] } To achieve this, I have the requirement of using the following code: var items = require("../../config/item.json"); The approach I am taking is ...

Are jQuery plugins offering accessible public functions?

I am currently working on enhancing the functionality of a jQuery plugin. This plugin serves as a tag system and utilizes autocomplete provided by jQuery UI. Presently, there is no direct method (aside from parsing the generated list items) to determine ...

Extract portions of the date into individual variables

My current project involves creating a front-end interface for data stored in a JSON database. The date information is saved in the following format: 12/31/16 I am trying to extract each of these values individually. Is there a method to assign variabl ...

Activate the Chrome Extension that allows you to open a link in a new tab with just a middle click or regular click, without closing the popup

When I try to click a link in my extension popup and open it in a new tab using "middle click -> open link in a new tab", the popup closes. Is there a way to keep the popup open so I can click on multiple links from my extension without interruption? A ...

Is there a way to stack multiple Divs on top of each other using Float instead of relying on absolute positioning?

I've decided to revamp my approach and transition from using absolute positions to utilizing floats for positioning elements the way I desire. Now the challenge lies in figuring out how to float multiple divs on top of each other, allowing users to s ...

Inquiry regarding the grid structure within my react application

When attempting to arrange my images in a grid layout, I encountered a strange issue after applying CSS grid. The grids ended up being organized horizontally instead of how I wanted them to be - two or three images per line. The component hierarchy is as ...

Solving Problems with Inline Tables using Angular, Express, and Mongoose's PUT Method

For the past few days, I've been struggling to figure out why my PUT request in my angular/node train schedule application isn't functioning properly. Everything else - GET, POST, DELETE - is working fine, and I can successfully update using Post ...

JavaScript: Discovering the art of "utilizing RESTful APIs"

After several years of coding in JS, I am now expanding my knowledge. I have noticed many job postings asking for familiarity with REST APIs and experience consuming RESTful services. I have a solid grasp on AJAX basics using both vanilla JS and jQuery. I ...

Consistently receiving the identical result even when the checkbox remains unselected

Displaying a Checkbox Input <input id="idCheckbox" name="check" type="checkbox" value="AllValue" style="width: auto; height: auto; font-weight: bolder;" data-bind="checked: idCheckbox" /> The checkbox input will always have the value "AllValue ...

Issue with text input field causing the Enter key to not create a new line

In the example above, the text is placed in the middle of the text area. Here is the CSS code : .form-control { height: 300px; display: block; width: 100%; padding: 0.375rem 0.75rem; font-size: 1rem; font-weight: 400; line-heig ...

What strategies can be utilized to condense code when needing to adjust a className based on various props?

I am looking to condense this code, particularly the [if~else if] block, in order to dynamically change a className based on different props passed. export default function Button(props) { const { name, height, color, bgColor } = props; let className = ...

JSONP - dealing with unsuccessful AJAX request callbacks

My current task involves transferring data from one domain to another using jsonp. The data transfer process on the second server seems to be functioning well. However, I am facing an issue with the callback function. Despite successfully receiving the dat ...

How to automatically redirect empty routes to a specific route in Next.js

When visiting a non-existent endpoint in Next.js, I receive a 404 error. What I actually want is for all unused routes to automatically redirect to a default route; specifically, the landing page. I've spent more than an hour trying to figure this ou ...

Having trouble with your jQuery image slider?

As a newcomer to jQuery, I have been experimenting with it to gain some experience. I recently tried to integrate a jQuery image slider from slidesjs.com into my local website but unfortunately, it is not functioning as expected. Additionally, I would lik ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...

Is it possible to showcase special characters retrieved from a MYSQL database using a modal form implemented in J

I am working on a jQuery code that retrieves data from MySQL and displays it in a modal window form. editRow: function(row){ var values = row.val(); ... $editor.find('#mail_username').val(values.mail_username); ... $modal.data('row', r ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...