$(this)

$(this)

  • this one of the most misunderstood concepts in JavaScript

  • this (native JavaScript) refers to the owner of a function

  • $(this) (jquery) gives you reference to uses jQuery to select the current element

We’ll cover the this (native JavaScript) in later in the course


Example

$(() => {
  $("#box").click(function() {
    // use $(this) with with regular function syntax
    // to reference the element that is being "acted on"
    $(this).fadeOut(1000)
  })
})

JS Bin on jsbin.com


  • The following is example of how a developer could go using javascript to implement an “active link” effect
$(function(){
  // store reference to ALL li elements that are children of ul.nav
  let $links = $('ul.nav li')

  // Add click event to each link
  // using special jquery object $(this)
  // to reference each element that was matched


  $links.on('click', function(){

    // Remove the active class from all links
    $links.removeClass('active')

    // Add the active class to the link that was clicked
    // which is refererenced by $(this)
    $(this).addClass('active')
  })

})

JS Bin on jsbin.com


$(this) can only be used with “regular functions”

  • $(this) can only be used in conjunction with regular function syntax and will not work with arrow functions

  • This is due to the difference in the way regular functions (using function keyword) and arrow functions (=>) create a private scope (we’ll go deeper into this concept later in the course)

Example: Using $(this) with arrow functions

  • This will not work because of the way arrow functions create local scope
  $("#box").click(() => {
    // use $(this) with with an arrow function
    // this will not work
    $(this).fadeOut(1000)
  })

JS Bin on jsbin.com


Exercise: Fix the Todo List using $(this)

  • Fix the Todo List application below so clicking on a single item will only toggle the item that was selected and not toggle all of the items
$(function(){

  // 1) Add a click event to each span element
  $('.todo li span').click(function(){

    // 2) Add toggleClass method to the span
    // that is clicked so its class will toggle
    // ".done" on and off
     $('.todo li span').toggleClass("done")
   })
})

JS Bin on jsbin.com