Over a million developers have joined DZone.

jQuery Code Snippets for Responsive Websites

DZone's Guide to

jQuery Code Snippets for Responsive Websites

If you code web apps, you've almost certainly used jQuery before. Read on to learn some cool tricks that jQuery has that allow devs to optimize their apps.

· Web Dev Zone ·
Free Resource

Learn how Crafter’s Git-based content management system is reinventing modern digital experiences.

When building a responsive website or app, jQuery can be of great help. In fact, it can take the whole 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 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's 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) {

Detect Viewport Size

CSS media-queries allow you to detect the viewport size and apply different CSS styling 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 get 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 drop-down menu.

The code below will get items from nav and append them to a select drop-down:

// 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"),

        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 implementing 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 the 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:


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

Crafter CMS is a modern Git-based platform for building innovative websites and content-rich digital experiences. Download this white paper now.

javascript ,web dev ,jquery

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}