0

I have lots and lots of code written already for the website that I'm launching soon, but I forgot one really important thing. The hover effect doesn't work correctly on mobile. I know that it kind of works when you click it, but that's not what I want. I want a touchstart and touchend effect for mobile. Is there an easy JavaScript code that can fix all the hover effects? Because it's not just about one class hover effect, there are many. Like the button effect and the flip cards that will flip when you hover them.

There is too much code to post here, but here is a link to my dummy site.

Is there anyone who can help me solve my problem, please? I know this is kind of a basic question, but I see so many different things on the internet that I don't know what to do. I can't write a Javascript code for every hover effect that's on the side. I also don't know how to fix it with the media query (hover: hover) or (hover: none) because I want a touch start and touchend effect.

Hope someone has the time to help me, it would mean a lot to me. Thank you in advance.

Deepak Singh
  • 749
  • 4
  • 16
Noa
  • 1
  • 1
  • something like https://stackoverflow.com/questions/13090285/touchstart-and-touchend-to-simulate-hover-or-mouseup-and-mousedown? – Suraj Rao Apr 10 '23 at 05:07
  • Yeah but that means I have to create a script for every class that has an hover effect right? – Noa Apr 10 '23 at 05:26
  • There is no css pseudo elements for touch. – Suraj Rao Apr 10 '23 at 05:32
  • U can select all the elements that have a hover effect using the querySelectorAll method and then loop through each element and add ontouchstart and ontouchend event listeners to trigger the touch effect. – NooberBoy Apr 10 '23 at 05:40

1 Answers1

0

Yes, there is a solution to achieve touchstart and touchend effects on mobile devices for hover effects using JavaScript. You can use the ontouchstart and ontouchend events to trigger the touch effect on mobile devices.

const elements = document.querySelectorAll('.hover-effect');

elements.forEach((element) => {
  // Add touchstart event listener
  element.addEventListener('touchstart', () => {
    element.classList.add('touch-hover-effect');
  });

  element.addEventListener('touchend', () => {
    // Remove touch effect
    element.classList.remove('touch-hover-effect');
  });
});

When the user touches the element, the touchstart event listener adds a touch-hover-effect class to the element, which can be used to apply the touch effect using CSS. When the user releases the touch, the touchend event listener removes the touch-hover-effect class from the element that you have added using touch-start.

I hope this helps!

For further reference: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events

Effect can be seen: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events#result

NooberBoy
  • 152
  • 2
  • 11