Guide for manually initiating the mouseleave event on a smartphone or tablet

Is there a way to change the color of a link to orange when it's hovered over?

On mobile devices, the link should turn orange when touched and stay that way until the user clicks away. I'd like to manually trigger the mouseout event to remove the hover effect after 1 second.

I attempted the following code but the link remains orange even after 1 second:

$(window).on('load', function() {
  $('a').on('click', function() {
    
    // For mobile devices, I want to stop the hover effect after 1 second
    window.setTimeout(function() {
      $('a').trigger('mouseout');
    }, 1000);
  
  });
});
a {
  font-size: 2rem;
}

a:hover {
  color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <a href='#'>Test</a>
</div>


Please note: this is just an example. In my actual code, I need to trigger the mouseout event on ajaxcomplete instead of using a timer.

$(document).on('ajaxComplete', function () {
    $('a').trigger('mouseout');
});

Answer №1

It appears that attempting to trigger a mouseout event on a touch device is not effective.

On touch devices, the sequence of events begins with a touchstart event as explained in MDN

If both touch and mouse events are generated by a single user input, the browser must initiate a touchstart event prior to any mouse events.

This code snippet detects when a touch event has been initiated by the user and alters the text color by adding a specific class instead of responding to mouse events. Similarly, it handles mouse events only if no touch interaction is detected on the element.

Although one might expect the touchend event to be triggered after releasing a long-touch on an anchor element, it seems that the touchend event does not occur on the element itself in such cases. However, the touchend event still occurs at the window level, allowing for the removal of the hover class.

let usingTouch = false;
const a = document.querySelector('a');
a.addEventListener('touchstart', function() {
  usingTouch = true;
  a.classList.add('hover');
});
window.addEventListener('touchend', function() {
  usingTouch = true;
  setTimeout(function() {
    a.classList.remove('hover');
  }, 1000);
});
a.addEventListener('mouseover', function() {
  if (!usingTouch) a.classList.add('hover');
});
a.addEventListener('mouseout', function() {
  if (!usingTouch) a.classList.remove('hover');
});
a {
  font-size: 2rem;
}

.hover {
  color: orange;
}
<div>
  <a href='#'>Test</a>
</div>

Answer №2

a {
  font-size: 2rem;
}

a:hover {
  color: myanimation 1s 1;
  -webkit-animation:myanimation 1s 1;
}

@keyframes myanimation
{
    0%      {color:orange;}
    100%    {color:orange;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <a href='#'>Test</a>
</div>

This particular issue can be resolved using a CSS animation, as demonstrated in the code snippet above.

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

Is it detrimental to my search engine ranking if I utilize CSS display:none?

Imagine having valuable content that is initially hidden with CSS, and then using javascript to reveal it only when the user clicks on certain links. Even users without javascript enabled can access this content by following the links to a new page where i ...

The data point on jqPlot does not display in full

I've been working on creating a chart with jqPlot to display data for each hour. It's mostly going well, but there's an issue where the first and last data points are not showing correctly - part of the circle is getting cut off. Here' ...

Utilizing Ajax to retrieve an array of input textboxes and showcase the outcome within a div container

This is the form that I have designed for displaying information: <form name='foodlist' action='checkout' method='POST'> <table> <tr> <td>Product Name</td> <td>Price</t ...

Customize MUI 5 input label background color for your own component

Struggling with overriding the background color for a MUI 5 input label on focus in a specific component? I successfully changed it to blue globally in my _theme.js file, but now need to make it red for my KeywordSearchTextField in index.js following MUI ...

Proceed to the next request after the initial request has finished executing in node

Imagine there is an endpoint called /print. Each time a request is sent to this endpoint, it triggers the function printSomething(). If another user hits this endpoint while printSomething() is still processing, it will run the function again simultaneousl ...

Collaboratively utilizing resources among various NPM Workspaces

Currently, I am working on a React project using NPM Workspaces. I have created an 'assets' workspace within this project to store all images and assets that need to be accessed by other workspaces. The directory structure of the project is as fo ...

Insert well-formed JSON into an HTML element

I'm facing a challenge while trying to dynamically embed a valid JSON array into HTML. The issue arises when the text contains special characters like quotes, apostrophes, or others that require escaping. Let me illustrate the problem with an example ...

trouble fetching ajax information

Help needed with ajax data retrieval issue on different browsers: Success in IE 7/8 Failure in FF 3.5/3.6, Chrome 5.0.375.70 The jquery code snippet used is pretty basic: $.get('http://myhost/someurl',function(data) { if (data) { ...

Learn how to display two different videos in a single HTML5 video player

Seeking a solution to play two different videos in one video element, I have found that only the first source plays. Is jQuery the answer for this problem? HTML Code: <video autoplay loop id="bbgVid"> <source src="style/mpVideos/mpv1.mp4" type ...

How can I update getServerSideProps using a change event in Next.js?

Currently, I am faced with the task of updating product data based on different categories. In order to achieve this, I have set up an index page along with two components called Products and Categories. Initially, I retrieve all products using the getServ ...

Solution: "The Mongoose Model.find method consistently provides an empty result set."

Currently, I am utilizing mongoose in combination with next.js to interact with an existing collection. Despite the collection not being empty, the mongoose model.find() function consistently returns an empty array. Below is my model code: const mongoose ...

Is the detailedDescription missing from the JSON-LD schema crawl?

I am currently utilizing the Google Knowledge Graph Search (kgsearch) API to retrieve Schemas from schema.org. However, I am encountering an issue where some nested elements are not being recognized as JSON or I may be overlooking something... url = "http ...

jQuery AJAX request delivering duplicate data

My jQuery ajax call is loading some elements into a div, but I am facing an issue where it returns duplicated responses. Instead of getting two elements as expected, I receive four (the 2 correct items, duplicated once). Below is the code snippet of my aj ...

Modifying property values using the onError event when encountering an error with the MUI DateTimePicker and

My goal is to set the 'myError' variable to true when MUI DateTimePicker throws an onError event, but for some reason it's not working. The code itself seems correct because if I replace () => {setValue({ ...value, ...

How to place a button in SwiperJs using React

Can anyone provide guidance on how to position the navigation buttons in a manner similar to the image below? The desired layout is for the buttons to appear on the outer edges of the swiper component. You can refer to this demo for more information. htt ...

Fetching real-time Twitter search feeds through dynamic AJAX requests

Previously, I successfully used JSON to retrieve hash tag feeds from Twitter and Facebook. However, currently the feeds are not updating dynamically, indicating a need for Ajax implementation. Unfortunately, my lack of knowledge in Ajax is hindering this ...

What is it about the phone screen that makes media content so captivating?

My phone has a resolution of 2280x1080. I noticed that when using the following code, the background color changes to blue on my phone: @media (max-width: 500px) { body { background-color: blue; } } Interestingly, this feature stops working once "compute ...

Trigger the click() event in jQuery before the blur() event

Looking to implement autocomplete suggestions in an input field? Take a look at the code below: <input type="text" id="myinput"> <div id="myresults"></div> To hide the results' div on the input's blur event, you can use this c ...

Using Angular function to retrieve Firebase snapshot

Trying to access a user's profile image stored in Firebase at /user/[uid]/info/photoURL This is being done using Angular functions. Here is the code snippet: HTML: <img ng-src="{{getImg(user.uid)}}" alt=""> Javascript: $scope.getImg = func ...

Detecting whether a browser is capable of supporting dark mode

One method to determine if dark mode is active is by using prefers-color-scheme: dark: const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; Is there a way to detect if a browser supports dark mode as well? (By "supports ...