Giter VIP home page Giter VIP logo

jquery-tips-everyone-should-know's Introduction

jQuery Tips Everyone Should Know Awesome

A collection of simple tips to help up your jQuery game.

For other great lists check out @sindresorhus's curated list of awesome lists.

Table of Contents

Tips

  1. Use noConflict()
  2. Checking If jQuery Loaded
  3. Check Whether an Element Exists
  4. Use .on() Binding Instead of .click()
  5. Back to Top Button
  6. Preload Images
  7. Checking If Images Are Loaded
  8. Fix Broken Images Automatically
  9. Post a Form with AJAX
  10. Toggle Classes on Hover
  11. Disabling Input Fields
  12. Stop the Loading of Links
  13. Cache jQuery Selectors
  14. Toggle Fade/Slide
  15. Simple Accordion
  16. Make Two Divs the Same Height
  17. Open External Links in New Tab/Window
  18. Find Element By Text
  19. Trigger on Visibility Change
  20. AJAX Call Error Handling
  21. Chain Plugin Calls
  22. Sort List Items Alphabetically
  23. Disable Right-Click

Use noConflict()

The $ alias used by jQuery is also used by other JavaScript libraries. To ensure that jQuery doesn't conflict with the $ object of different libraries, use the noConflict() method at the start of the document:

jQuery.noConflict();

Now you'll reference the jQuery object using the jQuery variable name instead of $ (e.g., jQuery('div p').hide()). If you have multiple versions of jQuery on the same page (not recommended), you can use noConflict() to set an alias to a specific version:

let $x = jQuery.noConflict();

back to table of contents

Checking If jQuery Loaded

Before you can do anything with jQuery you first need to make certain it has loaded:

if (typeof jQuery == 'undefined') {
  console.log('jQuery hasn\'t loaded');
} else {
  console.log('jQuery has loaded');
}

Now you're off...

back to table of contents

Check Whether an Element Exists

Prior using a HTML element you need to ensure it's part of DOM.

if ($("#selector").length) {
  //do something with element
}

back to table of contents

Use .on() Binding Instead of .click()

Using .on() gives you several advantages over using .click(), such as the ability to add multiple events...

.on('click tap hover')

...a binding applies to dynamically created elements, as well (there's no need to manually bind every single element dynamically added to a DOM element)...

...and the possibility to set a namespace:

.on('click.menuOpening')

Namespaces give you the power to unbind a specific event (e.g., .off('click.menuOpening')).

back to table of contents

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

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 with scrollTop.

back to table of contents

Preload Images

If your web page uses a lot of images that aren't visible initially (e.g., on hover) it makes sense to preload them:

$.preloadImages = function () {
  for (var i = 0; i < arguments.length; i++) {
    $('<img>').attr('src', arguments[i]);
  }
};

$.preloadImages('img/hover-on.png', 'img/hover-off.png');

back to table of contents

Checking If Images Are Loaded

Sometimes you might need to check if your images have fully loaded in order to continue on with your scripts:

$('img').on('load', function () {
  console.log('image load successful');
});

You can also check if one particular image has loaded by replacing the <img> tag with an ID or class.

back to table of contents

Fix Broken Images Automatically

If you happen to find broken image links on your site replacing them one by one can be a pain. This simple piece of code can save a lot of headaches:

$('img').on('error', function () {
  if(!$(this).hasClass('broken-image')) {
    $(this).prop('src', 'img/broken.png').addClass('broken-image');
  }
});

Alternatively, if you wish to hide broken images this snippet will take care of that for:

$('img').on('error', function () {
  $(this).hide();
});

back to table of contents

Post a Form with AJAX

jQuery AJAX methods are a common way to request text, HTML, XML, or JSON. If you wanted to send a form via AJAX you could collect the user inputs via the val() method:

$.post('sign_up.php', {
  user_name: $('input[name=user_name]').val(),
  email:     $('input[name=email]').val(),
  password:  $('input[name=password]').val(),
});

But all of those val() calls are expensive and using .val() on <textarea> elements will strip carriage return characters from the browser-reported value. A better way of collecting user inputs is using the serialize() function which collects them as a string:

$.post('sign_up', $('#sign-up-form').serialize());

back to table of contents

Toggle Classes on Hover

Let's say you want to change the visual of a clickable element on your page when a user hovers over it. You can add a class to your element when the user is hovering; when the user stops hovering removes the class:

$('.btn').on('hover', function () {
  $(this).addClass('hover');
}, function () {
  $(this).removeClass('hover');
});

You need to add the necessary CSS. If you want an even simpler way use the toggleClass method:

$('.btn').on('hover', function () {
  $(this).toggleClass('hover');
});

Note

CSS may be a faster solution in this case but it's still worthwhile to know this.

back to table of contents

Disabling Input Fields

At times you may want the submit button of a form or one of its text inputs to be disabled until the user has performed a certain action (e.g., checking the "I've read the terms" checkbox). Add the disabled attribute to your input so you can enable it when you want:

$('input[type="submit"]').prop('disabled', true);

All you need to do is run the prop method again on the input, but set the value of disabled to false:

$('input[type="submit"]').prop('disabled', false);

back to table of contents

Stop the Loading of Links

Sometimes you don't want links to go to a certain web page nor reload the page; you might want them to do something else like trigger another script. This will do the trick of preventing the default action:

$('a.no-link').on('click', function (e) {
  e.preventDefault();
});

back to table of contents

Cache jQuery Selectors

Think of how many times you write the same selector over and over again in any project. Every $('.element') selector has to search the entire DOM each time, regardless if that selector had previously run. Instead you can run the selector once and store the results in a variable:

var blocks = $('#blocks').find('li');

Now you can use the blocks variable wherever you want without having to search the DOM every time:

$('#hideBlocks').on('click', function () {
  blocks.fadeOut();
});

$('#showBlocks').on('click', function () {
  blocks.fadeIn();
});

Caching jQuery selectors is a good performance gain.

back to table of contents

Toggle Fade/Slide

Sliding and fading are common in animations with jQuery. You might want to show an element when a user clicks something, which makes the fadeIn and slideDown methods perfect, but if you want that element to appear on the first click and then disappear on the second, this will work fine:

// Fade
$('.btn').on('click', function () {
  $('.element').fadeToggle('slow');
});

// Toggle
$('.btn').on('click', function () {
  $('.element').slideToggle('slow');
});

back to table of contents

Simple Accordion

This is a simple method for a quick accordion:

// Close all panels
$('#accordion').find('.content').hide();

// Accordion
$('#accordion').find('.accordion-header').on('click', function () {
  var next = $(this).next();
  next.slideToggle('fast');
  $('.content').not(next).slideUp('fast');
  return false;
});

By adding this script all you really need to do on your web page is the necessary HTML to get this working.

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();
  }
});
$columns.height(height);

If you want all columns to have the same height:

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

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

Open External Links in New Tab/Window

Open external links in a new browser tab or window and ensure links on the same origin open in the same tab or window:

$('a[href^="http"]').attr('target', '_blank');
$('a[href^="//"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');

back to table of contents

Find Element By Text

By using the contains() selector in jQuery you can find text in content of an element. If text doesn't exists, that element will be hidden:

var search = $('#search').val();
$('div:not(:contains("' + search + '"))').hide();

back to table of contents

Trigger on Visibility Change

Trigger JavaScript when the user is no longer focusing on a tab or refocuses on a tab:

$(document).on('visibilitychange', function (e) {
  if (e.target.visibilityState === 'visible') {
    console.log('Tab is now in view!');
  } else if (e.target.visibilityState === 'hidden') {
    console.log('Tab is now hidden!');
  }
});

back to table of contents

AJAX Call Error Handling

When an AJAX call returns a 404 or 500 error, the error handler will be executed. If the handler isn't defined, other jQuery code might not work as intended. To define a global AJAX error handler:

$(document).on('ajaxError', function (e, xhr, settings, error) {
  console.log(error);
});

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:

$('#elem').show();
$('#elem').html('bla');
$('#elem').otherStuff();

This could be vastly improved by using chaining:

$('#elem')
  .show()
  .html('bla')
  .otherStuff();

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

var $elem = $('#elem');
$elem.hide();
$elem.html('bla');
$elem.otherStuff();

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

back to table of contents

Sort List Items Alphabetically

Let's say you end up with too many items in a list. Maybe the content is produced by a CMS and you want to order them alphabetically:

var ul = $('#list'),
lis = $('li', ul).get();

lis.sort(function (a, b) {
  return ($(a).text().toUpperCase() < $(b).text().toUpperCase()) ? -1 : 1;
});

ul.append(lis);

There you go!

back to table of contents

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

Support

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

back to table of contents

Translations

back to table of contents

jquery-tips-everyone-should-know's People

Contributors

102 avatar adhamu avatar allthingssmitty avatar colinodell avatar danielsychoo avatar girasquid avatar lalaithan avatar lockys avatar marcjansen avatar mattjared avatar mikestreety avatar nunofca avatar semicolonexpected avatar shangyusu avatar smoqadam avatar ve00ryca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-tips-everyone-should-know's Issues

TOC needed

This will make it easier to parse through tips.

Translations

I'm setting up this card as a way to track PR's for language translations. If you're translating this repo please add a comment indicating which language so we're not duplicating work. 😎

Your PR should include the following:

  1. Add a language/country code folder to the translations folder, e.g., translations/fr-FR
  2. Add a README.md file with the translation to the language/country code folder, e.g., .../fr-FR/README.md

You can find more information about contributing under the Language Translations section of the Contribution Guidelines.

I'm not looking for pasting into Google Translate; I can do that myself and it's not accurate. 💁🏼 I appreciate your help with this. 👍🏼


Translations (and any others that may not be on this list):

  • Bulgarian (bg-BG)
  • Chinese - simplified (zh-CN)
  • Chinese - traditional (zh-TW)
  • Czech (cs-CZ)
  • Danish (da-DK)
  • French (fr-FR)
  • German (de-DE)
  • Gujarati (gu-GU)
  • Hungarian (hu-HU)
  • Italian (it-IT)
  • Japanese (ja-JP)
  • Korean (ko-KR)
  • Polish (pl-PL)
  • Portuguese - Brazilian (pt-BR)
  • Portuguese - European (pt-PT)
  • Russian (ru-RU)
  • Spanish (es-ES)
  • Turkish (tr-TR)

Ajax calls enhancement

When using an Ajax call, always use an error handler!
When an ajax call returns a 404 or 500 error, the error handler will be executed. If the handler is not defined, sometimes other javascript/jquery wont work anymore. I'm not sure if this is the case with jquery 2, but I have seen this problem before.

You can define a global ajax error handler in jquery by:

$(document).ajaxError(function(e, xhr, settings, error){
    console.log(error);
});

Some issues

Just raising this, because though it's nice to provide snippets for people (or their mothers), it's not nice to provide bad/mis information.

Deprecated methods

You're using the deprecated (since jQuery 1.8!) old syntax for binds, e.g.

$('something').error(function () {});

You should be using the .on() syntax:

$('something').on('error', function () {});

This affects the following:

  • .error()
  • .load()
  • .click()

Setting an element property

You should be using .prop() to set the disabled property, since jQuery 1.6:

$('input').prop('disabled', true);

From the docs for .prop():

The .prop() method is a convenient way to set the value of properties—especially when setting multiple properties, using values returned by a function, or setting values on multiple elements at once.

Using JavaScript where CSS will do

I take umbrage with your :odd example, because this can and should be done completely in CSS:

li:nth-child(odd) {
  background: #e8e8e8;
}

All modern browsers support CSS3 selectors, and if you've got to support older browsers you could apply classes in your HTML, rather than depending on jQuery for a visual effect.

Making two elements the same height

This example works if you know which element will be the largest, but a better, more flexible method would be to loop over a set of elements, and set the height for them to the height of the tallest element:

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

Need version for father

Are there any plans in the works to release a guide for fathers? Obviously this one won't work because the lessons all teach techniques that are helpful exclusively to moms and address uniquely female programming issues. TIA

License

The lack of a license probably means a good few people are shying away from using the examples provided. Thoughts on this?

Typo

Preload Images section:

it's make sense to

to

it makes sense to

Add CONTRIBUTING section

It's a smart idea to help others know what would be good to include with PR's, e.g., JS snippet, README update, format, etc.

Crossbrowsing toTop

I think the right way to do toTop animation is through the selector $('html, body') for crossbrowsing purpose, i.e.:

$(document.body).animate({scrollTop: 0}, 800);

Re-attach events when the DOM reloads. EG: on ajax pagination

When you load content through ajax (or pjax), and events are registered on elements inside that content. The events registered are not handled anymore. Because the previous DOM elements are 'destroyed'. The events should be re-attached on the DOM elements. A best practice is to attach the events on a global DOM element.
For Example:

<div id="content">
   <!-- this content will be changed with ajax //-->
</div>

Instead of attaching the events on the elements within the content, attach the events on the DOM element which will NOT be loaded or changed through ajax (in this case: #content, or sometimes: body).

$('#content').on('click', 'a', function(e){
    // here the logic when clicking on a link inside the `#content` div
});

Few jQuery tips inside your tips!

Hey, sorry to raise this like an "issue", I didn't seem to find anywhere else to send you this message...

For the "Make two (or more) DIVs the same height" for example, you could use a much smaller version of code if you use Math and Array.map (in this case the "map" function that jQuery provides). Like this:

var maxHeight = Math.max.apply(null, ($("div").map(function(){ return $(this).height(); })));
$("div").height(maxHeight);

As you can see, jQuery also doesn't need you to iterate through the nodes to set their properties, you can set the property for a selection of nodes, all at once.

Hope this is helpful!

Regards,
Cristian.

Re-enabling disabled form fields

You currently advocate removeAttr('disabled') for re-enabling disabled form fields. When jQuery first came out, attr() was the only way to modify the disabled state, and the proper way was indeed to use removeAttr(). Since jQuery 1.6, prop('disabled', true) is the right way to make an input disabled and prop('disabled', false); is the right way to re-eanble it (not removeAttr('disabled')).

http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/
https://jquery.com/upgrade-guide/1.9/#attr-versus-prop-

On hover

Don't want to create a pull request so I created an issue :)

$('.btn').hover(function () {
$(this).addClass('hover');
}, function () {
$(this).removeClass('hover');
});

should be

$('.btn').hover(function () {
$(this).toggleClass('hover');
});

Preload Images Possible Bug

You have this code to preload images:

$.preloadImages = function () {
  for (var i = 0; i < arguments.length; i++) {
    $('img').attr('src', arguments[i]);
  }
}

If I'm not mistaken, that should set every image on the page to the last image passed, since you select all the images with $('img').

To create an in memory element each time, use $('<img>')

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.