For those still looking for a way to do this, I have a solution:
First you can detect whether the device is a touch screen by detecting if the primary input type is pointer: coarse
(answer from https://stackoverflow.com/a/52855084)
Then, if the device is a touch device, count how many times the link has been clicked. On the first click, prevent the default behaviour using .preventDefault()
, and the dropdown should open but not the link. On the second click, don't suppress this behaviour and the link will open.
So, define a variable to keep track of the count, add your on click function to the link and prevent the default action if it is the first click:
var dropdown_clicked = 0;
//for touchscreens, click 1 = open dropdown, click 2 = open link
$("#dropdown > a").on('click', function (e) {
if(window.matchMedia("(pointer: coarse)").matches) {
//pointer:coarse = touchscreen
dropdown_clicked += 1;
if (dropdown_clicked == 1){
e.preventDefault();
}
if (dropdown_clicked == 2){
dropdown_clicked = 0;
}
}
Make sure your functions are defined within $(document).ready(function(){ });
as this method uses jQuery.
For context, I have this method for opening the dropdown on
hover:
$("#dropdown").hover(function () {
//slideToggle = display or hide the matched elements with a sliding motion
//stop(true,true) stops the animation from repeating
$(this).find('ul').stop(true, true).slideToggle('medium');
});
And the dropdown HTML:
<ul>
<li><a href="index.php">home</a></li>
<li id="dropdown"><a href="page.php">my dropdown</a>
<ul>
<li>dropdown content</li>
<li>dropdown content</li>
</ul>
</li>
</ul>