Track Jquery Tips Everyone Should Know Updates Weekly

A collection of tips to help up your jQuery game 馃幃

馃彔 Home馃攳 Search馃敟 Feed馃摦 Subscribe鉂わ笍 Sponsor馃樅 AllThingsSmitty/jquery-tips-everyone-should-know猸 4.2K馃彿锔 Front-End Development

[ Daily / Weekly / Overview ]

Jun 19 - Jun 25, 2017

Disable Right-Click

If you want to disable right-click, you can do it for an entire page...

$(document).ready(function () {
  $(document).bind('contextmenu', function (e) {
    return false;

...and you can also do the same for a specific element:

$(document).ready(function () {
  $('#submit').bind('contextmenu', function (e) {
    return false;

back to table of contents

Current versions of Chrome, Firefox, Safari, Opera, Edge, and IE11.

back to table of contents

back to table of contents

May 02 - May 08, 2016

Back to Top Button

By using the animate and scrollTop methods in jQuery you don't need a plugin to create a simple scroll-to-top animation:

// Back to top
$('.container').on('click', '.back-to-top', function (e) {
  $('html, body').animate({scrollTop: 0}, 800);
<!-- Create an anchor tag -->
<div class="container">
  <a href="#" class="back-to-top">Back to top</a>

Changing the scrollTop value changes where you wants the scrollbar to land. All you're really doing is animating the body of the document throughout the course of 800 milliseconds until it scrolls to the top of the document.

[!NOTE] Watch for some buggy behavior (猸317) with scrollTop.

back to table of contents

Make Two Divs the Same Height

Sometimes you'll want two divs to have the same height no matter what content they have in them:

$('.div').css('min-height', $('.main-div').height());

This example sets the min-height which means that it can be bigger than the main div but never smaller. However, a more flexible method would be to loop over a set of elements and set height to the height of the tallest element:

var $columns = $('.column');
var height = 0;
$columns.each(function () {
  if ($(this).height() > height) {
    height = $(this).height();

If you want all columns to have the same height:

var $rows = $('.same-height-columns');
$rows.each(function () {

[!NOTE] This can be done several ways in CSS but depending on what your needs are, knowing how to do this in jQuery is handy.

back to table of contents

Chain Plugin Calls

jQuery allows for the "chaining" of plugin method calls to mitigate the process of repeatedly querying the DOM and creating multiple jQuery objects. Let's say the following snippet represents your plugin method calls:


This could be vastly improved by using chaining:


An alternative is to cache the element in a variable (prefixed with $):

var $elem = $('#elem');

Both chaining and caching methods in jQuery are best practices that lead to shorter and faster code.

back to table of contents