jQuery code snippets for responsive websites

jQuery code snippets for responsive websites

When building a responsive website or app, jQuery can be of great help. In fact, it can take the whole mobile user experience to a new level. In this article, I have compiled my favorite jQuery tips and tricks for making and enhancing responsive sites.


Scroll to an element

Scrolling endlessly on a smartphone isn’t the most fun thing ever. This is why it can be very useful to set scrolls so your visitors won’t need to take 10 seconds to reach the info they’re looking for.

Let start with an auto-scroll: The code below will programmatically scroll to a specific element on the page:

$('html, body').animate({
    scrollTop: $("#target").offset().top
}, 1000);

Now, let’s set a scroll that the user will activate by clicking on a link:

$('a#source').on('click', function(event) {
    $('body').scrollTo('#target');
});

Detect viewport size

CSS media-queries allow you to detect the viewport size and apply different CSS style to elements depending on the viewport width.

This can also be done in jQuery, and it can be very useful to achieve results you couldn’t using CSS alone. The following example shows how to detect the viewport width, and subsequently add an element to a list.

if ($(window).width() < 960) {
    $( "ul.mylist").append("<li>One more list element</li>");
}

Turn navigation menu into a dropdown

When your website features many menu items, it can be tricky to display on small screens. Therefore, an easy fix to this problem is to turn a navigation into a dropdown menu.

The code below will get items from nav and append them to a select dropdown:

// Create the dropdown base
$("<select />").appendTo("nav");

// Create default option "Go to..."
$("<option />", {
   "selected": "selected",
   "value"   : "",
   "text"    : "Go to..."
}).appendTo("nav select");

// Populate dropdown with menu items
$("nav a").each(function() {
 var el = $(this);
 $("<option />", {
     "value"   : el.attr("href"),
     "text"    : el.text()
 }).appendTo("nav select");
});

$("nav select").change(function() {
  window.location = $(this).find("option:selected").val();
});

Source: CSS Tricks

Animate Height/Width to “Auto”

If you have tried using thing.animate({ "height": "auto" }); on an element, you've noticed that it didn't work. Happily, there's a quick and efficient fix to this problem.

Here's the function:

jQuery.fn.animateAuto = function(prop, speed, callback){
    var elem, height, width;
    return this.each(function(i, el){
        el = jQuery(el), elem = el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
        height = elem.css("height"),
        width = elem.css("width"),
        elem.remove();
        
        if(prop === "height")
            el.animate({"height":height}, speed, callback);
        else if(prop === "width")
            el.animate({"width":width}, speed, callback);  
        else if(prop === "both")
            el.animate({"width":width,"height":height}, speed, callback);
    });  

And how to use it:

$(".animateHeight").bind("click", function(e){
    $(".test").animateAuto("height", 1000); 
});

$(".animateWidth").bind("click", function(e){
    $(".test").animateAuto("width", 1000); 
});

$(".animateBoth").bind("click", function(e){
    $(".test").animateAuto("both", 1000); 
});

Source: CSS Tricks

Lazy load images

Lazy loading is a technique that forces a page to only load images which are visible on the clients' screen. It has proven to be very effective for improving your website loading speed, which is extremely important in terms of user experience and SEO.

There are lots of jQuery plugins dedicated to implement lazy loading on your site. If you're using WordPress, I definitely recommend this one.

As for jQuery lazyload plugins, I've been using this one, simply called Lazy Load, on a few sites. It's usage is very easy. The first step is to import the plugin into your HTML page:

<script src="https://cdn.jsdelivr.net/npm/lazyload@2.0.0-beta.2/lazyload.js"></script>

Now the HTML code: By default Lazy Load assumes the URL of the original high resolution image can be found in data-src attribute. You can also include an optional low resolution placeholder in the src attribute.

<img class="lazyload" data-src="img/example.jpg" width="765" height="574">
<img class="lazyload" src="img/example-thumb.jpg" data-src="img/example.jpg" width="765" height="574">

It's now time to activate the lazy loading. The following will lazy load all images with the .lazyload class:

lazyload();

There are indeed many more options available, so just have a look at the plugin documentation.