Loading...

Blog

How to add a Specific Class for Touchscreen Devices using JavaScript

With the rapid evolution of smartphones and tablets, web designers have had to quickly adapt and pick up new techniques in order to develop websites that work seamlessly across multiple devices with varied resolutions. Responsive design has evolved as the most popular way to achieve this. During the course of coding a responsive project there are times when you might need a specific class to target certain changes for only smartphones, tablets, or other touchscreen devices. In this tutorial we will teach you a very simple method utilizing JavaScript to add a specific class to target only touchscreen devices.

Step 1: Adding the Javascript

Simply copy and paste the JavaScript below inside the head of your website:

$(document).ready(function() {
     if ("ontouchstart" in window || "ontouch"; in window) { $('body').addClass('touch'); } 
});

What does this script do?
This script will now add the class ‘touch’ to the body tag of your website only if the device utilizes a touchscreen.

Step 2: Call the ‘Touch’ Class with CSS

Now anytime you need to make specific changes for touchscreen devices throughout your code you can simply override default styles by putting body.touch in front of it. See the example below:

#header{ background: #fff;  }
body.touch #header{ background: #000; }

In the example above the background color of the header is set to white (#fff) as default and on any touchscreen device the header’s background color will now be overridden to black (#000).

Troubleshooting

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible. Please do not email us with problems regarding this tutorial, only comments will be responded to.

Leave a Comment

3 comments
webreality_ny
webreality_ny

You have an extra semicolon after "ontouch". Thanks for this snippet.

efforts1234
efforts1234

Thanks for telling. I had a problem in designing responsive website.