Black Bytes
Help more people learn by sharing this post!

Jquery tips & tricks

If you have done any web work at all you have probably used jQuery. Let’s go over some jQuery tips that you may find useful.

jquery tips

Post a form with ajax

A very common use for jQuery is AJAX. If you want to send a form via AJAX one thing you could do is this:

Aren’t all those .val() calls annoying you a bit? There is a better way to do this using the serialize function:

Toggle a div

If we want to have a “folding” div with a header that shows/hides the contents when we click on it we can do this:

First we check if the content is already showing via the display css property, then we call the .slideDown function for a little animation and change the arrow image to point down. Here is a demo.

jQuery and Coffeescript

If you decide that you would like to start using coffeescript, here is what jQuery in coffeeescript looks like:

Just pay attention to the indentation level and you should be fine :)

Turbolinks + jQuery

Rails 4 comes with turbolinks enabled by default, what turbolinks does is replace the body of your site via AJAX when you click a link instead of reloading the whole page. While this will make your page appear to load faster to the user it has a small problem: it doesn’t trigger the document.ready event.

You will find that some of your js code breaks when using turbolinks because of this. Turbolinks triggers the page:load event, so we can hook our code to that, here is an example (coffeescript syntax):

Conclusion

Hate it or love it, but jQuery can be very useful and it takes care of differences between browsers (in terms of javascript stuff).

Make sure to check the docs when you have any doubts: http://api.jquery.com/. You may also find this alternative documentation useful: http://jqapi.com/.

Do you have other cool jQuery tips that you use often? Share them in the comments (you may want to use gist or jsfiddle for you code)!