jQuery Basics

Why use jQuery?

jQuery is a JavaScript library, it works on top of JavaScript to simplify things

jQuery has to be added before the JS you write that uses it. It's basically declaring a variable $, that you can use in your code.

You can either download and load jQuery locally along with your other JS file, or you can use a CDN: jQuery CDN

You select a variable with the jQuery shortcut command ($)

		var $jquerySelectedElement = $("#test-id");
	

Remember that what you're passing to the $ function is a string with the CSS selector:

This won't work:

$(#id)

This will:

$('#id')

Once selected, the element can now use jQuery methods. You can see a full list at jQuery API. Some common ones are CSS(), hide(), and show()

jQuery's documentation can be a little overwhelming, but they provide good examples. Don't be discouraged if there are speedbumps. You can always try Googling "How do I _____ with jQuery?" StackOverflow will usually have great answers.

		$jquerySelectedElement.css('color', 'red');
	

Look what did to this p tag with an id of test-id

We used jQuery's CSS method and passed it 2 strings: the first was the CSS property we wanted to change, the 2nd the new value for that property.

But jQuery's real power comes in making it easier to create and respond to EVENTS. Like when a user clicks or hovers over an element:

		$("#alert-button").click(function() {
			alert("You clicked the button!");
		});
	

We select the #alert-button with $, then use the click method, passing that a function that contains the code we want to execute.

Click the button below to change the styles of this paragraph.

This paragraph gets hidden and shown when you click the button below!