Front End Engineering, May 2015

  • ready
  • find
  • on
  • $var
  • chaining
  • jQuery object
  • addClass

Why jQuery

  • Selecting elements
  • DOM manipulation
  • Event handling
  • Ajax
  • Cross browser development

jQuery

  • select elements (use the $() function, returns the jQuery object)
  • read methods (e.g. $('div').text())
  • write methods (e.g. $('body').append(someElement))
  • $(this) is a common pattern in event handlers
  • It's useful to cache queries:

      var $items = $('.my-list li');
      $items.addClass('highlighted');
      setTimeout(function(){
        $items.removeClass('highlighted');
      }, 1000);
    
  • $(document).ready(function(){}) and $(function(){})

Events

In jQuery event handlers, the value of this is the element that the event was triggered on.

jQuery

Avoid changing appearance with jQuery

  • .css $('.container').css('color', 'red')
  • .animate
  • .fadeIn, .fadeOut
  • slideUp, slideDown
  • .show, .hide

Event handlers

// ''.cool' is the selector that you're handling events on
// $('.cool') is returning a jQuery object that wraps the '.cool' 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. One property of note is event.target.
// this is the element that the event was triggered on (the .cool element in this case).
// $(this) is wrapping the element with jquery so we can call jquery methods on it.
$('.cool').on('click', function(){
  $(this).toggleClass('ice-cold');
})

Event Object

http://api.jquery.com/category/events/event-object/