You can use CSS media queries for that. To detect a mouse, your query would look like that:
@media (hover: hover) and (pointer: fine) {
// 'hover' means a device that supports hovering
// 'pointer: fine' means an accurate pointing device, as opposed to limited pointing device like touchscreen (where you would use 'coarse' value
}
Note that this query will detect touch pad as well but it will not detect smartphones, touchscreens, stylus-based screens or other controllers like Nintendo Wii, Microsoft Kinect.
To run the same query from JavaScript, you can use Window.matchMedia()
:
if (matchMedia('(hover: hover) and (pointer: fine)').matches) {
// You code
}