Skip to content

Instantly share code, notes, and snippets.

@jennceng
Last active August 10, 2016 00:40
Show Gist options
  • Save jennceng/ebf741ac46b7da1001d471c40cfc269f to your computer and use it in GitHub Desktop.
Save jennceng/ebf741ac46b7da1001d471c40cfc269f to your computer and use it in GitHub Desktop.

based off a simple side project menu preferences the WIP git repo

The following is adapted from my mentor, Elise Fitzgerald!

#Intro to jQuery Library

jQuery is a JavaScript library. jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

There is also another extension library called jQuery UI that provides some nice effects and methods for enhanced user experiences.

Where to Start: New Learning Center!

jQuery is a very popularly used library and beyond documentation the authors of jQuery have launched a (beta) Learning Center that approached documentation in beginner friendly way.

####Cautionary Tale Everything you can do in jQuery is written with regular (sometimes jokingly called "vanilla") JavaScript. Therefore, understanding the fundamentals of JavaScript as a language (its constructs and syntax, its orientation to particular programming concepts) is important (it's not just us telling you - the learning docs even say so!) in order to effectively use jQuery. You want to be careful not to use jQuery as a crutch to avoid engaging with the internals of JavaScript and instead use it as a tool to expedite your work.

How to set up in a Rails

rails new and done!

Rails comes with jQuery included as well as jQueryUI.

In Sinatra

If you are adding it in a Sinarta app, you can check out this repository for directions.

There are two key ways:

Note on Syntax

The $ is the same as including jQuery before the selector. For example, $('h2') is the same as jQuery('h2') the $ here denotes the library. jQuery being among the most popular libraries it's safe to include the dollar sign in all referees. But be aware that other libraries may also use the $ which could through you errors down the road or a namespace collision, at which point you should refer to the jQuery documentation on this topic.

First grab the jQuery object

There are a number of ways to "grab" selectors from the DOM, notice the similarity to css:

  • By id $("#chart-1");
  • By class $(".top-bar");
  • By element $("h1");

Assigning a jQuery object to a variable

You can assign any element you select with jQuery to a variable and then call jQuery methods on it.

var chart = $('#chart-1')
chart.hide();

Pro-tip: Don't mix with Vanilla JS

When "grabbing" elements from the DOM with jQuery we are returned jQuery objects. We can call jQuery effects and events on jQuery objects but not if we "grab" them with JS. The below results in an error:

var vanilla = document.getElementById("chart-1")
vanilla.hide();

Then have fun with that object

To get some inspiration and decide what to do once you grab the item or items you want from the page, check out the jQuery API documentation.

Hiding an element

$("#chart-1").hide();

hide() documentation

Showing an element

$("#chart-1").show();

show() documentation

GET FANCY! FADE OUT!

$("#chart-1").fadeOut();

fadeOut() documentation

Changing the styling of element(s)

$("h1").css("color", "teal");

css() documentation

or maybe:

$(".top-bar").addClass("new_class");
$(".top-bar").addClass("feature");

Why did the top bar disappear? let's take a look at the css for the class "feature"

addClass() documentation

Remove an element and then append it somewhere else

var chart = $('#chart-1').remove();
$('.ingredients').append(chart);

Remove is different from hide, remove takes it out of the DOM

remove() documentation

append() documentation

Append something new to a list

var annoyingAd = "YOU SHOULD BUY KITTEN MITTENS: BUILDING A QUIETER CAT"
$("ul").append("<li>" + annoyingAd + "</li>")

How to use within Rails

Good practice to add files for different features but that's where you can run into some issues. For the app size you guys are using it's good to keep in one file for now.

  • Let's look at our Rails set up
  • We have a application.js linked in our layout

PRO-TIP ALERT: $(document).ready();

Loading your JavaScript at the bottom of the page will help you avoid trying to manipulate elements that aren't yet loaded onto the page, but $(document).ready(); is an insurance policy against this problem. It's particularly useful for images or other content which may load after a js file at the end of the <body> or in the <footer>.

It's best to only use one or fewer $(document).ready(); in your js file as you get started. While technically you can use more than one, it is slightly slower (an optimization concern), more verbose (a style/readability concern) and arguably harder to debug (a developer experience concern). It also gets you into the habit of organizing your code into discrete functions.

function someFunction(){
  //do a thing;
};

function someOtherFunction(){
  //do some other thing;
};

$(document).ready(function(){
  //someFunction();
  //someOtherFunction();
});

Let's Try it Out!

Let's add these features:

####Toggle the form

$(".new_customer h1").click(function() {
  $("#new_customer").toggle();
});

Append something new to list from form field, reset field

var newIngredient = $("#ingredient_name").val();
$("ul").append("<li>" + newIngredient + "</li>");
$("#ingredient_name").val("");

Notice how the above syntax for grabbing the value is different syntactically then vanilla JS. The last line resets the name field to be an empty string. If you refresh the page, whatever you added will be lost because we did not add it to the database so the data was not able to persist...BUT... stay tuned for AJAX :) Side note: you'll notice the item was added near the top bar as well, this is because there's a ul in my topbar so $("ul") is selecting both unordered lists in the DOM, just an fyi.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment