Detecting mousedown on dektop and touchstart on mobile devices with javascript

This short JavaScript jQuery code detects MouseDown / MouseUp event on desktop browsers and it handles TouchStart / TouchEnd events on touchscreen devices. We need this because MouseDown never fires on touch devices and vice versa TouchStart never triggers on devices using mouse pointer.

detect mousedown desktop touch devices

The jQuery Code

$(document).ready(function () {
    var isTouchDevice = 'ontouchstart' in document.documentElement;
    
    $("#touchSensitive").mousedown(function(event) {
        if (isTouchDevice == false) {   
            pushed();   
        }
    });
    $("#touchSensitive").mouseup(function(event) {
        if (isTouchDevice == false) {   
            released(); 
        }
    });
    $('#touchSensitive').on('touchstart', function(){
        if (isTouchDevice)  {   
            pushed();   
        }
    });
    $('#touchSensitive').on('touchend', function(){
        if (isTouchDevice)  {   
            released(); 
        }
    });
});

We place the script in the $(document).ready section which is run once when the Document Object Model (DOM) is ready for JavaScript code to execute.
The isTouchDevice variable carries a true/false value, whether the device is a touch device or not. In my example the pushed() function is called on touch start and mouse down, while the released() is executed then the mouse click or the touch ends.