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
$(() => {
$("#box").click(function() {
// use $(this) with with regular function syntax
// to reference the element that is being "acted on"
$(this).fadeOut(1000)
})
})
$(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')
})
})
$(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)
$("#box").click(() => {
// use $(this) with with an arrow function
// this will not work
$(this).fadeOut(1000)
})
$(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")
})
})