When we add a hover effect to an element in CSS, it sticks in touch devices. In this article, we will learn how to solve this issue.
There are two possible approaches to solve this problem –
Without Using JavaScript: It can be solved by using a media query in CSS. The condition ‘hover: hover’ refers to the devices that support hover. Using media query along this condition ensures that the below CSS is added only on such devices.
Code snippet:
@media(hover: hover) { #btn:hover { background-color: #ccf6c8; } }
This adds a hover effect only on hover-enabled devices, which means no hover effect is applied on touch devices. Here the background color of the button is changed on hover.
Example: This example shows the above-explained approach.
html
< style > #btn { background-color: #0dad78; margin: 3%; font-size: 30px; } @media (hover: hover) { #btn:hover { /*Add hover effect to button on hover enabled devices*/ background-color: #ccf6c8; } } </ style > < button type = "button" id = "btn" > Submit </ button > |
Output:
Using JavaScript: In this method, we will use JavaScript to determine if we are on a touch-enabled device using the below function. The ontouchstart event returns true when the user touches an element. The navigator.maxTouchPoints returns a maximum number of simultaneous touchpoints supported by the device. The navigator.msMaxTouchPoints also has the same function with the vendor prefix “ms” to target browsers IE 10 and below.
Thus the given function returns true if the device is touch-enabled. (To read more about the function refer: https://www.geeksforgeeks.org/how-to-detect-touch-screen-device-using-javascript/)
function is_touch_enabled() { return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0); }
If touch is not enabled, we add a class to our button. This class adds a hover effect to the button in CSS as described in the below example:
Example: This example shows the above-explained approach.
html
< style > #btn { background-color: #0dad78; margin: 3%; font-size: 30px; } .btn2:hover { background-color: #ccf6c8 !important; /*Hover effect is added to btn2 class*/ } </ style > < body onload = "hover()" > < button type = "button" id = "btn" >Submit</ button > < script > function hover() { function is_touch_enabled() { // Check if touch is enabled return "ontouchstart" in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; } if (!is_touch_enabled()) { // If touch is not enabled, add "btn2" class var b = document.getElementById("btn"); b.classList.add("btn2"); } } </ script > </ body > |
Output: