jQuery is a free, open-source JavaScript library designed to make DOM manipulation easier.
A note from the jQuery website: "One important thing to know is that jQuery is just a JavaScript library. All the power of jQuery is accessed via JavaScript, so having a strong grasp of JavaScript is essential for understanding, structuring, and debugging your code. While working with jQuery regularly can, over time, improve your proficiency with JavaScript, it can be hard to get started writing jQuery without a working knowledge of JavaScript's built-in constructs and syntax."
- Discuss libraries/frameworks, how to include them in your HTML. Include jQuery and test to make sure it's being loaded in properly.
- Examine the difference between JavaScript and jQuery selectors — particularly the data types returned.
- Start converting JS we've written in class and labs to jQuery.
- Styling — practice changing CSS properties, hiding and showing elements.
- Events - discuss the various event listeners in JS, practice implementing them in jQuery.
- Discuss homework!
Because jQuery is an external library, we have to include it in our HTML in order for our custom JS to utilize it.
To do so, we use a script tag just like we would our own JS files:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
You'll notice the url provided on jQuery's site (or any other CDN: Google, Microsoft, etc) does not include "http" or "https", and instead just begins with "//". This is called a "protocol relative URL", meaning it will load whether a user is acessing via http or https.
We must take care to include this script tag BEFORE any custom JS that makes use of the jQuery library, because of the order in which browsers parse HTML:
<html>
<head>
</head>
<body>
...
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="main.js"></script>
</body>
</html>
The first thing we'll want to do to begin accessing the power of jQuery is learn how to select elements.
In JavaScript, the functions we used were getElementById, getElementsByClassName, and getElementsByTagName. These are quite tedious to type out and come with their own host of inconveniences (like having to separate out elements from the arrays returned by ClassName and TagName).
jQuery selectors are much simpler to use, and look almost identical to CSS selectors, just wrapped in jQuery's "object notation". An object wrapper in jQuery begins with a dollar sign and contains its selector within parentheses and quotes, like so:
$("selector")
Just like in CSS, we can select an element via its tag name, which returns any matching elements on the page:
$("div")
or class with CSS's dot notation:
$(".class-name")
or id with CSS's pound notation:
$("#id-name")
or attribute with CSS's attribute notation (though do this with caution, as it is a very costly operation):
$("input[value="one"]")
or selector combinations:
$("nav ul.menu li#home")
or **pseudo-selectors:
$("img:visible")
is that element there? if element.length
Our Javascript code:
document.getElementById('box1').style.borderRadius = '50%';
in jQuery:
$('#box1').css('border-radius', '50%');
.css
The css function, like many JavaScript functions, can be used as both a getter and a setter. What makes this one unique is that is not recommended to use it as a setter, as setting styles in JavaScript breaks the separation of concerns principle. For that reason, it's best to create classes in CSS and add or remove them in JavaScript to achieve presentational changes.
It can be very useful to retrieve information about element styles, however, as a getter:
if ($('element').css('display') == 'none'){
// do something
}
Our JavaScript code:
function addClass(selector, newClass){
if (type == "class"){
var elems = document.getElementsByClassName('selector');
for(var i = 0; i < elems.length; i++){
elems[i].className = elems[i].className + " " + newClass;
}
}
else if(type == "tag"){
var elems = document.getElementsByTagName('selector');
for(var i = 0; i < elems.length; i++){
elems[i].className = elems[i].className + " " + newClass;
}
}
else{
var elem = document.getElementById('selector');
elem.className = elem.className + " " + newClass;
}
}
function removeClass(selector, classToRemove){
if (type == "class"){
var elems = document.getElementsByClassName('selector');
for(var i = 0; i < elems.length; i++){
elems[i].className = elems[i].className.replace(new RegExp('(?:^|s)' + classToRemove + '(?!S)'), '');
}
}
else if(type == "tag"){
var elems = document.getElementsByTagName('selector');
for(var i = 0; i < elems.length; i++){
elems[i].className = elems[i].className.replace(new RegExp('(?:^|s)' + classToRemove + '(?!S)'), '');
}
}
else{
var elem = document.getElementById('selector');
elem.className = elem.className.replace(new RegExp('(?:^|s)' + classToRemove + '(?!S)'), '');
}
}
in jQuery:
$('elem').addClass('newClass');
$('elem').removeClass('classToRemove');
$('elem').toggleClass('class');
Our JavaScript code:
function hide(selector, type){
if (type == "class"){
document.getElementsByClassName(selector).style.display = "none";
}
else if(type == "tag"){
document.getElementsByTagName(selector).style.display = "none";
}
else{
document.getElementById(selector).style.display = "none";
}
}
function hide(selector, type){
if (type == "class"){
document.getElementsByClassName(selector).style.display = "block";
}
else if(type == "tag"){
document.getElementsByTagName(selector).style.display = "block";
}
else{
document.getElementById(selector).style.display = "block";
}
}
in jQuery:
$('element').hide();
$('element').show();
$('element').toggle();
A lot of what we've learned up until now has dealt with programming fundamentals (functions, data structures, etc), but what really lies at the heart of JavaScript is reacting to user input. We touched briefly last week on adding event listeners using pure JS that call functions when an element is clicked. jQuery makes event listeners stupid simple, so let's take a look at a few of them:
.click()
The click function can be used either as an event listener (as we used it last week) or to trigger a click on an element.
// event listener added to element, triggers function on click
$('element').click(function(){
alert($('elmenent').innerHTML);
});
// event listener added to element, triggers click on second element on // click
$('element').click(function(){
$('element2').click();
});
.keydown()
The keydown function can be used to execute some code anytime a key is pressed. A common usecase for this is in forms, to submit them if a user presses the enter key rather than clicking a submit button:
$('input').keydown(function(e){
// .which returns the keycode
if (e.which == 13){
$('form').submit();
}
});
.scroll()
The scroll function can be used to detect a user's scroll and fire off some code accordingly. Let's alert the user when they've scrolled a certain distance down the page:
$(window).sroll(function(){
if ($(window).pageOffsetY() > 2000){
alert('you've scrolled 2000 pixels!');
}
});
http://api.jquery.com/category/events/
http://www.smashingmagazine.com/2012/05/31/50-jquery-function-demos-for-aspiring-web-developers/
https://css-tricks.com/snippets/css/keyframe-animation-syntax/
Revisit the checkPassword homework from week 3 and add a .keydown event so that the password is checked when you press enter, the same as it would be having clicked the check button.
Using the same HTML, CSS, and JavaScript documents from last week's homework, let's make a few changes:
- Include the jQuery library
- Convert any vanilla JS to jQuery (selectors, click listeners, function references).
- Add a new event listener that on click of a box toggles a class "selected".
- Add a new button called "select all" that toggles the class "selected" on all the boxes.
- Rewrite hide, show, and color button functions to only be applied to boxes with the class "selected".
- Add a new button called "spin" that will toggle a class on the selected boxes to make them spin.
CSS to add:
.selected{
border:2px solid blue;
}
@-moz-keyframes spin {
from { -moz-transform: rotate(0deg); }
to { -moz-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
from { -webkit-transform: rotate(0deg); }
to { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
.spin{
-webkit-animation: spin 2s linear;
-moz-animation: spin 2s linear;
-o-animation: spin 2s linear;
animation: pin 2s linear;
}