Wednesday, 25 April 2012

jQuery: how to use it only for mobile


Developing responsive web sites is not always easy. We have seen something about it with media queries, but that was aimed to managing CSS stylesheets. Today I'm going to show you how to deal with jQuery.

I've found the following trick somewhere on the web, but I don't remember where, so if you are the author please leave a comment and I will give you credit for it.

Let's try to clear up a bit the situation. We want to trigger some jQuery or, generally speaking, some JavaScript code just when the visit is coming from a smartphone. Because we know that those devices mainly have a screen width of 480px, we are going to use that as condition.

Main solution
Said that, it is quite easy to implement the solution. We basically have to check the screen width and then run the code:

    if (jQuery(window).width() <= 480) {
As you can see, we use window.width  in jQuery to determine if the width is less or equal to 480. If so, we can insert our code (replace yourCodeHere with your jQuery code).
The above solution is easy and effective, but there's another way of doing it.

A different solution
Instead of using jQuery directly, we can trigger JavaScript including the code only for target devices. To do so, we can use Modernizr and specifically its mq method (media query testing):
" tests a given media query, live against the current state of the window."
In order to conditionally load the external js file, we use a simple snippet:
  test:'only screen and (max-width: 480px)'),
  yep : 'yourJSfile',
  complete : function () {
        //call the function inside yourJSfile
As you can see, we load yourJSfile only when the screen max width is 480px. After that, we use the code inside the loaded file.

And that's all for today.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.