How do you add an event Mouseover (hover) on touch devices using jQuery?

| | 2 min read

Recently I ran into the problem of mouseovers on touch devices. In short, they doesn't exist. I had just created a layout of four images which listed at the centre of the home page as like our zyxware website. And if you check the site on mouseover the image it will expand and while clicking the image it will go to the link added. But the problem is the mouse over wont work on the touch mobile devices.

Consider three image blocks are present in the site as image 1, image 2, image 3. So if the user mouse over the image 1 it should exapnd to the full size and if he clicks on the image it should go to the repective link added to the image. In touch devices there is no mouse over so it is like it sould expand if the user clicks it first and it should go to the link if the user clicks the same image second. It is like the following.

  • User taps image 1 again -> image 1 is opened.
  • User taps image 2 -> mouseover for image 2 is activated and the mouseover for image 1 is deactivated.

Another thing we have to keep in mind is that if a user taps image 1, then taps image 2 and then taps image 1 again, it should not consider image 1 as being tapped for a second time (which would lead to the browser to open the link). Accomplishing this requires a ‘flag’ which indicates the last tapped link: if the last tapped link equals the currently tapped link we have a ‘double tap’ and the link should be opened.

Example:

  HTML
  
     &ltdiv id="parent-element"&gt
      &lta href="image1.com" id="image1"&gtimage 1&lta&gt
      &lta href="image2.com" id="image2"&gtimage 2&lta&gt
      &lta href="image3.com" id="image3"&gtimage 3&lta&gt
    &ltdiv&gt
  
  jQuery
  
    $('#parent-element a').live("touchstart",function(e){
      var $link_id = $(this).attr('id');
      if ($(this).parent().data('clicked') == $link_id) {
        $(this).parent().data('clicked', null);
        return true;
      } else {
        $(this).trigger("mouseenter").siblings().trigger("mouseout");
        e.preventDefault(); 
        $(this).parent().data('clicked', $link_id); 
      }
    });
  

I solved this using an event called "touchstart", and added the event to the parent element of the anchor tag which contains the images. Selected the link id as clicked at first and after the image gets viewed I am setting the link id value as null. So that the if else statement will esecute alternaltely by the tappings which the user who visit the site does. We can also use has class and add class to do the same steps instead of link_id here. In the else statement you can notice the mouse enter and mouse leave events. In that line I am giving mouse enter function for the one image which I clicked and mouse leave for all the rest siblings.