Detecting a mobile browser (Device Sniffer) with javascript

I recently created a custom cursor for a website that looked like this:

What I wanted to make sure, was that this custom cursor did not appear on touch screen devices.

The solution:


//set a variable to check if the device has a touchscreen
var hasDeviceTouch = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);


//if the device does not have a touch screen, then run the code that controls the custom cursor
if (!hasDeviceTouch ) {
const cursor = document.querySelector('.cursor');
document.addEventListener('mousemove', e => {
cursor.setAttribute('style', 'top: '+(e.pageY - 6 )+'px; left: '+(e.pageX - 6)+'px;');
})
}

Finally, where I called the cursor div on the main page, I added this code so as to only output the source code to pages that did not have a touch screen:


if (!hasDeviceTouch ) { document.write("< div class='cursor'>"); }

Leave a Reply

Your email address will not be published. Required fields are marked *