- use an IIFE to avoid polluting the global namespace
- identify common DOM methods used in jQuery methods
- Practice DOM manipulation w/ vanilla js
Today, I'll be coding on the server - meaning you'll have access to my code instantly!
Remember to refresh the page for the latest changes.
http://www.wdidc.org/~jesse/jquery-from-scratch/jakeWeary.js
We know jQuery is a function because typeof $ === "function"
var $ = function(selector){
return document.querySelector(selector)
}
$(".box") // returns a DOM element
Immediately invoked function expressions allow us to keep many variables and function names private to a particular file.
var $ = (function(){
var jakeWeary = function(selector){
return document.querySelector(selector)
}
return jakeWeary
})()
// typing jakeWeary in the console gives uncaught reference error
var $ = (function(){
var jakeWeary = function(selector){
var el = document.querySelector(selector)
el.on = function(eventName, callback){
el.addEventListener(eventName, callback)
}
return el
}
return jakeWeary
})()
Currently, the on method only handles one element.
Replace document.querySelector
with document.querySelectorAll
Inside the on
method, loop through each of the elements to add
the event listener
els.css = function(props){
for(var i = 0; i < els.length; i ++){
for(var key in props){
els[i].style[key] = props[key]
}
}
}
Update the .css
method to allow the alternate css syntax:
$(".box").css('background','red')
- Add a second argument to method
- check the
typeof
the first argument - if It's a
string
, update the value - otherwise, use the existing code
$(".box").on("click", function(){
$(this).css({'background':'red'})
})
this
is already a DOM element, not a selector
var jakeWeary = function(selector){
var els = selector.nodeName ? [selector] : document.querySelectorAll(selector)
...
var shoesToWear = itIsRaining ? "galoshes" : "sandals"
// is equivalent to
if(itIsRaining){
var shoesToWear = "galoshes"
} else {
var shoesToWear = "sandals"
}
els.html = function(){
for(var i = 0; i < els.length; i++){
return els[i].innerHTML
}
}
- Add a new argument to HTML method
- if the argument is not undefined, update the
innerHTML
with the argument's value
- Define a new method
val
- If no arguments are given, return the element's value
- If one argument is given, set the element's value to the provided argument.
Count off 1-4
- find(), siblings(), children()
- hide(), show(), toggle()
- append(), prepend()
- addClass(), toggleClass()