1

I created a custom Navbar which is working perfectly. My problem lies within which functionality to use based on the device in action. For touchscreen devices I would like to use the click function, and for keyboard devices hover. I have two scripts both for hover and click events for my Navbar.

Click

<script>
$( '.tc-navigation > li' ).click(function() {
$(this).children('ul').toggleClass('toto');
$(this).siblings().children('ul').removeClass('toto');   
return false;
});

$(document).click(function() {
$('.tc-navigation > li > ul').removeClass('toto');
});
</script>

For Hover

<script>
$( '.tc-navigation > li' ).hover(function() {
$(this).children('ul').toggleClass('toto');   
});
</script>

Can anybody please assist how I can figure out the type of device used as well as how to implement the already written scripts at hand?

Jed Richards
  • 12,244
  • 3
  • 24
  • 35
Nigussu Sima
  • 127
  • 8
  • Possible duplicate of [How to recognize touch events using jQuery in Safari for iPad? Is it possible?](https://stackoverflow.com/questions/4755505/how-to-recognize-touch-events-using-jquery-in-safari-for-ipad-is-it-possible) –  Aug 10 '18 at 14:32

1 Answers1

0
  1. First, you need a way to detect, whether device is mobile or not:

    function isMobile() {
      return /Mobile/.test(navigator.userAgent); // do some research if "Mobile" always occurs in userAgent string if you want to be sure
    }
    
  2. Based on that you can choose your event:

    var event = isMobile() ? "click" : "mouseover";
    
  3. Use event variable to attach proper listener. In vanilla JS you would do something like this:

    element.addEventListener(event, doStuff);
    

I don't use jQuery, so I'll leave that for you to figure out, but i think what you would look for here is .on() method - read here

Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18