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.
A very common use for jQuery is AJAX. If you want to send a form via AJAX one thing you could do is this:
|
1 2 3 4 5 |
$.post("test.php", { user_name: $("input[name=user_name]").val(), email: $("input[name=email]").val(), password: $("input[name=password]").val(), }); |
Aren’t all those .val() calls annoying you a bit? There is a better way to do this using the serialize function:
|
1 |
$.post("/users/sign_up", $("#signup-form").serialize()); |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
$("#faq_header").click(function() { header_open = $("#faq_content").css('display') == 'block'; if (header_open) { $("#faq_content").slideUp("slow"); $("#faq_header img").attr("src", "/img/arrow_down.png"); } else { $("#faq_content").slideDown("slow"); $("#faq_header img").attr("src", "/img/arrow_up.png"); } }); |
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.
If you decide that you would like to start using coffeescript, here is what jQuery in coffeeescript looks like:
|
1 2 3 4 |
$ -> $("#btn-confirm").on "click", (e) -> alert('button clicked!') e.preventDefault() |
Just pay attention to the indentation level and you should be fine 
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):
|
1 2 3 4 5 |
ready -> // your code here $(document).ready(ready); $(document).on('page:load', ready); |
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)!