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

jQuery AJAX request encounters a 406 Error

<p I'm experiencing some frustration as I encounter a 406 error when making an AJAX request on my hosting server (Linux), but not on my local machine (Windows 7). Both environments are using Apache. All other requests with similar formats ...

Exploring the Transition from React.js with Material UI to Next.js for Server-Side Rendering: A Comparison of Tailwind CSS, Material UI, and Chakra UI

Currently, I am in the process of moving my React.js application with Material UI components to Next.js for server-side rendering (SSR) while considering some UI changes. In my research, I have come across three UI frameworks: Material UI, Chakra UI, and T ...

Using Array.Map() to retrieve the child array within a React component

Here is the data I have retrieved from an API: [ { "id": 1, "appName": "string", "defaultAction": "string", "defaultMessage": "string", "rules": [ { "id": 1, "version": "string", "brand": "string", ...

Arranging Boxes side by side

I am struggling to align three boxes horizontally on my website, as they are currently stacking vertically. I have implemented Twitter Boostrap's 'row' class in an attempt to achieve this layout. HTML: .img-box-kai { width: 300px ...

What steps should I take to address a situation in which a Protractor test becomes stuck indefinitely?

I've encountered an issue with a test case that was previously running successfully but is now getting stuck indefinitely during execution. This problem occurs each time the test attempts to click on a specific element, causing the test to hang withou ...

What is the typical number of open CLI terminals for a regular workflow?

After experimenting with Gulp, Bower, ExpressJS, and Jade, I have settled on a workflow that I am eager to switch to. The only issue I am facing is the need to have two terminals open simultaneously in order to use this workflow efficiently. One terminal ...

Extend the row of the table according to the drop-down menu choice

I am working on a feature where a dropdown menu controls the expansion of rows in a table. Depending on the option selected from the dropdown, different levels of items need to be displayed in the table. For example, selecting level 1 will expand the first ...

"Why is it that the keypress event doesn't function properly when using the on() method

My goal is to capture the enter event for an input field $("input[name='search']").on("keypress", function(e){ if (e.which == '13') { alert('code'); } }); This is the HTML code snippet: <input name="searc ...

AngularJS: How to detect the browser's refresh event

Can AngularJS detect when the user clicks the Refresh button on the browser? Is there a built-in method in the framework for developers to access? Thank you ...

AngularJS directive does not trigger when switching tabs or scrolling pages

I came across a solution to display a placeholder image before the real image fully loads while browsing online here. I implemented the code provided in the accepted answer on my page, where I have two tabs using `ion-slide-box` for tab selection. Each tab ...

The offset values of $(element) keep increasing indefinitely when they are updated repeatedly

After researching how to utilize JavaScript drag functionality to move elements, the goal is to dynamically adjust the cursor position within a square when dragged. In an attempt to simplify the process and avoid storing x and y offsets as separate variabl ...

Employing jQuery to append a fresh hierarchy of parent divs

I'm just starting to learn jquery and I have a question about this scenario, <div id="parent"> <div class="child1">Child 1 Contents</div> <div class="child2">Child 2 Contents</div> </div> I am trying to crea ...

Issue with onclick event not being triggered by Javascript function inside constructor

My current challenge involves implementing a function called makeHighlight within the SmartButton constructor. The purpose of this function is to execute whenever I click on the SmartButton object, which is represented by an image element. To achieve thi ...

Tips for updating multiple bundled javascript files with webpack

I am working on a straightforward app that requires users to provide specific pieces of information in the following format. Kindly input your domain. User: www.google.com Please provide your vast URL. User: www.vast.xx.com Select a position: a) Bottom ...

JSON: Automatically choose the radio button based on the provided response

Is there a way to automatically select the checked state of radio buttons based on data retrieved from a database? I need to populate this form's radio button with data <div class="col-md-4"> <label> <input type="radio" name="m ...

Encountering an issue with eslint-loader in a new VueJS project: TypeError - eslint.CLIEngine is not recognized as

Embarking on a fresh VueJS venture with WebStorm. A brand new VueJS project has been established, NPM upgraded, Vuetify added, and upon server initiation, an error pops up: ERROR Failed to compile with 1 errors ...

"Execute asynchronous tasks in Javascript and receive the returned

Currently, I am utilizing JSF ajax within my application and unfortunately, we are unable to make any changes to that. In the process of waiting for user action, I find it necessary to prompt the user before executing the ajax method. Specifically, I need ...

Display/Conceal Title with Hover Effect in Fancybox2

I need assistance with hiding and showing the title in fancybox2 using the hover event. The code I have tried is not working properly. Here is my current code: $("#fancybox-wrap").hover(function() { $("#fancybox-title").show(); }, functio ...

Picture featuring a right-angled triangle on the right side

I have been experimenting with creating a complex image effect using CSS only, without any JavaScript. Despite several attempts, I haven't been able to achieve the desired outcome yet. CSS .container{ width: 500px; background-color: #0c2f45; ...

Adjusting the parent with CSS transitions to perfectly align with the final height of a

Jade example div.parent div.child1 div.child2 Upon initial load, Child1 is visible. Clicking will hide Child1 and make Child2 visible. Another click will reverse this action. During the transition between hiding and showing the children, there s ...