jQuery
Select elements
use the
$()
function$('.js-modal').addClass('is-active');
allows chaining
$('.js-show-image').addClass('is-active').addClass('is-shown');
Read information from the DOM
var total = $('h2.js-total').text()
var email = $('input.js-email').val()
var templateSource = $('#main-template').html()
Write information to the DOM
$('.js-total').text(10)
$('.js-email').val('[email protected]')
Add elements to the DOM
$('.container').html('<h1>Hello</h1>')
$('.container').append('<h1>Hello</h1>')
$('.container').prepend('<h1>Hello</h1>')
Kick off your application when the page is loaded
$(document).ready(function(){
// stuff that needs to access the DOM
});
Events
/*
`'.className'` is the selector that you're handling events on
`$('.className')` is returning a jQuery object that wraps the '.className' element(s).
`.on` is a method you're calling on the jQuery object
`'click'` is the event you're passing as an argument to .on, telling it which event to listen for
the `function(){}` is an anonymous function that you're passing to the .on method. The function will be called when the event is triggered.
`event` is a parameter to receive the event object that is generated by the event.
`this` is the element that the event was triggered on (the .className element in this case).
`$(this)` is wrapping the element with jquery so we can call jquery methods on it.
*/
$('.className').on('click', function(event){
$(this).toggleClass('is-active');
})