To detect if a user is using a touchscreen device, you will need to utilize some JavaScript (specifically jQuery, which is likely already integrated into your website) along with Modernizr. While there are alternative methods for checking touch compatibility, in my experience, Modernizr provides the most reliable outcomes.
Start by incorporating Modernizr into your project. You can either download it directly from their official website or use a content delivery network like cdnjs.com.
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.7.1/modernizr.min.js"></script>
Next, add the following JavaScript to your website:
$(document).ready(function(){
if(Modernizr.touch){
$('#menu-mainmenu').on('click', '> li', function(e){
if(!$(this).data('open')){
e.preventDefault();
}
$(this).data('open', true);
});
}
});
If a user is using a touch-enabled device and clicks on a main menu item, a submenu will appear (thanks to the :focus
styling). However, the link will be prevented from opening due to e.preventDefault()
. Subsequently, the 'open' data attribute is set to true. Consequently, if the user taps the link again, the conditional check will fail, and the link will open normally. Although I haven't tested this extensively, it should function as intended...