Wifi — First Round Capital Guest
Password (all lowercase) — frclovesphilly
Slides — ivanaveliskova.com/gdi-jquery
Demo Files — ivanaveliskova.com/gdi-jquery/demo-files.zip
Remember to unzip demo-files and place it somewhere easily accessible on your desktop!
Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.
Some "rules"
Slack is a free, chat and messaging system available as either a web or native application for your desktop or mobile device. All our welcome to join our Slack team, but we need to add you! For an invitation, sign up here.
Tell us about yourself.
Variables
var name = "Ivana";
var greeting = "Hey there, " + name;
console.log(greeting);
Open up the demo-files/js-review.html in your browser and text editor to test this out!
Don't forget to open up the console!
Data Types
var myString = "This is a string!";
var myInteger = 1;
var myBoolean = true;
var myArray = ["string", 1, myVar, true];
var myObject = {
name: "Pamela",
adjective: "Cool",
age: 25,
roles: ["hacker", "teacher", "coder"]
};
Looping
var favoriteThings = ["Puppies", "Doctor Who", "Settlers of Catan"];
for(var i = 0; i < favoriteThings.length; i++) {
console.log((i + 1) + ". " + favoriteThings[i]);
}
var i = 0;
while(i < 10) {
console.log("The current number is: " + i);
i++; // Don't forget to increment i or you will get stuck in an infinite loop!
}
Conditionals
var total = 10;
if (total >= 100) {
console.log("Total is greater than or equal to 100");
} else {
console.log("Total is less than 100");
}
Combining Conditionals and Looping (FizzBuzz)
for(var i = 1; i <= 100; i++) {
var print;
if ((i % 5) === 0 && (i % 3) === 0) {
print = 'FizzBuzz';
} else if ((i % 3) === 0) {
print = 'Fizz';
} else if ((i % 5) === 0) {
print = 'Buzz';
} else {
print = i;
}
console.log(print);
}
There is no single 'right' way of solving this. This is just one solution. When you have some time try to figure out a different solution!
Functions
var name = "Ivana";
function greet() {
var name = "Joey";
console.log("Hey there, " + name);
}
greet();
What will happen if we run this code?
Functions
function add(number1, number2){
console.log("Total: " + (number1 + number2));
}
add(2, 3);
add(1000, 30000);
var name = "Ivana";
function sayHelloTo(name){
console.log("Hello, " + name + "!");
}
sayHelloTo("Maggie");
sayHelloTo(name);
sayHelloTo();
Traversing the DOM
document.getElementById('above-paragraph');
// Finds an element in the DOM by ID
// will return first one that matches (there should only be 1)
document.getElementsByClassName('past');
// Finds elements in the DOM by class
// will return an array even if there is only one match
document.getElementsByTagName('body');
// Finds elements in the DOM by tag
// will return an array even if there is only one match
document.querySelectorAll('[data-slide]');
// Finds elements in the DOM by any selector that you can use in CSS
// will return an array even if there is only one match
document.querySelector('[data-slide]');
// Finds an element in the DOM by any selector that you can use in CSS
// will return only the first one that matches
We made it through the JS review!
Any questions?
To hide images:
var allImages = document.getElementsByTagName("img");
for (var i = 0; i < allImages.length; i++) {
allImages[i].style.display = "none";
}
To hide images:
$('img').hide();
.
Use a <script> tag
<script src="http://code.jquery.com/jquery-2.2.1.js"></script>
This HTML...
<img src="puppies.jpg">
with this jQuery...
$('img').hide();
results in this HTML...
<img style="display: none;" src="puppies.jpg">
$('img').hide();
$('img').hide();
$() Global jQuery function. Alternately "jQuery()". Used to trigger all jQuery functionality.
'img' Argument being passed into the global jQuery function. Also accepts variables and html strings. Returns a jQuery collection/object
.hide() jQuery method to hide the element by adding a style of 'display: none;'
; Syntax to conclude a statement
All CSS selectors are valid
Some Examples:
a all anchors
.blue elements with the class "blue"
p:eq(2) the third paragraph (zero-based count)
[id^="vidLink_"] elements with an id beginning with "vidLink_"
:contains("free") elements that contain the text "free" (case-sensitive)
[data-hide-image] elements that have the data attribute "data-hide-image"
There are many jQuery methods- like tools in a toolkit!
Like screwdrivers, hammers, wrenches, there are a few main groups that methods fall into:
So break it down even further, a method can be a getter, a setter, or both!
.hide() Adds an inline style of "display: none" to the element
.show() Adds an inline style of "display: block" to the element
.remove() Deletes element from the DOM
.html() Retrieves html within the selected element
.text() Retrieves only the text within the selected element
.parent() Retrieves the element's direct parent
.children() Retrieves all direct children of the element
.next() Retrieves the next single element at the same level in the DOM tree
.width() Returns the width of element (in px)
.height() Returns height of element (in px)
.fadeOut() Gradually decreases opacity of element and then add a "display: none"
.fadeIn() Will add a "display:block" and then gradually increase opacity of element
$('.hero img').remove();
$('#banner > span').hide();
$('#banner').children().hide();
$('img:not(.hero img)').fadeOut();
Let's try this in the console of our demo files!
.addClass('your-classname')–Adds your-classname as a class attribute on to the element
.removeClass('your-classname')–Removes your-classname as a class attribute on to the element
.attr('src')–Retrieves the src attribute for the element
.css('background-color')–Retrieves the background color of the element
.append('<p>The end!<p>')–Inserts a 'p' tag inside the element at the end
.prepend('<h1>Hey!</h1>')–Inserts an 'h1' tag inside the element at the beginning
$('.hero img').attr('src');
$('#banner > span').addClass('visible');
$('#banner').children().append('!');
Let's try this in the console of our demo files!
.html()–Retrieves html within element
.html('<h1>Hey!</h1>');–Inserts/Replaces html within element
.text()–Retrieves text within element
.text('Hey you!');–Inserts/Replaces text within element
.width()–Retrieves the width of element
.width(300)–Sets the width of the element to be 300px
.attr('src', 'sunset.jpg')—Finds the element's src attribute and changes its value to sunset.jpg
.css('background-color', 'green')—Finds the elements background color and changes it to green by adding an inline style, which overrides any background-color that might already be there .
Check the jQuery Documentation for info on how each method works!
<a href="http://www.google.com" style="color: green;">Google</a>
$('a').text(); "Google"
$('a').attr('href'); "http://www.google.com"
Trick question:
$('a').css('color'); "rgb(0, 128, 0)"
<a href="http://www.google.com" style="color: green;">Google</a>
$('a').text('Yahoo!');
$('a').attr('href', 'http://www.yahoo.com');
$('a').css({'color': 'purple', 'text-decoration': 'underline'}); .
<a href="http://www.yahoo.com" style="color: purple; text-decoration: underline;">Yahoo!</a>
Alternatively the javascript code above can be written as:
$('a').text('Yahoo!').attr('href', 'http://www.yahoo.com').css({'color': 'purple', 'text-decoration': 'underline'});
You can pile on as many methods as you need, as long as you keep track of what is happening. (And potentially can document it.)
In your demo-files javascript page, use jQuery to
Make sure to comment out the code that hid the images!!!
Bonus Challenge! Try to replace the text on the images in the gallery! (Start by changing all of the text to be the same and then try to make each line different)
Try not to modify the HTML/CSS directly (such as adding classes so you can select certain elements), try to only make the changes using jQuery
var $doc = $('body');
var style = $doc[0].style;
if ( style.msGrid === '' || style.grid === '' ) {
$doc.addClass("supports-grid");
}
And now you can be sure that your browser supports grid! And if you have the latest version of Chrome (57) or FireFox (52) you should be able to get this class to show up in the DOM!
<img class="sale-img" src="images/sale.png">
var currentTime = new Date().getTime();
// sets currentTime variable to current unix timestamp like 1428534443
var endDayBegin = new Date(2017, 4, 23).getTime();
var endDayEnd = new Date(2017, 4, 23, 23, 59, 59).getTime();
if (currentTime > endDayBegin && currentTime < endDayEnd) {
$('.sale-img').attr('src', '/images/ends-today.png');
} else if ( currentTime > endDayEnd ) {
$('.sale-img').remove();
}
// changes sale image to an 'ends today' version if it's the last day of the sale
// And removes the image if it's past the day
In javascript we wrote a 'for' statement and kept track of the index with a variable.
var listItems = document.getElementsByTagName('li');
for(var index = 0; index < listItems.length; index++) {
console.log('This is list item # ' + index);
}
With jQuery we can use...
.each() — commonly used method to loop through a collection
$('ul li').each(function(index) {
console.log('This is list item #' + index);
});
index: the function supplied to "each" is automatically passed the number of the current loop iteration, which will generally match the index of each member of the collection.
this: "this" is the context of any function. Frequently in jQuery, "this" will refer to the element being pointed to by the iterator.
Other built-in methods are sometimes passed other pertinent data.
Example coming right up!
"used to indicate a person, thing, idea, state, event, time, remark, etc., as present, near, just mentioned or pointed out…" — Dictionary.com
*Not really a sponsor.
Now back to your regularly scheduled programming.
Using 'this' as an iterator:
$('ul li').each(function() {
$(this).append('!');
});
To be more efficient, cache a variable for $(this):
$('ul li').each(function() {
var $self = $(this);
$self.append('!');
});
$('#someID').append('!');
$('#someID').css('color', 'green');
This will ask jQuery to rescan for the matching element, wrap it in a jQuery object, and create a new instance of something you already have in memory.
$someVarName = $('#someID');
$someVarName.append('!');
$someVarName.css('color', 'green');
This will allow you to cache your elements and refer to them when needed. Saving memory!
Now back to your regularly scheduled programming.
In demo-files/index.html, use .each() to credit each listed quote to David Tennant!
Challenge: Give credit at the beginning of each quote
Bonus Challenge! Take each image and make the overlay appear and disappear 'on' hover! Hint: try using the jQuery documentation (http://api.jquery.com/) to figure this out!
The bread and butter of jQuery.
When something happens
When I do this thing, it will respond somehow
$('#button').on('click', function() {
console.log('The button was clicked!');
});
You can also...
$('a').on('click', function (event) {
event.preventDefault();
console.log('Not going there!');
});
Event handlers are typically passed the event that has triggered them, and that data can then be used by the handler. See info on the event object: http://api.jquery.com/category/events/event-object/
You can also use the "on" method to bind to multiple events at once:
$('.overlay').on('click touchstart', function() {
$(this).fadeToggle('slow');
});
$('.sidebar').on({
click: function() {
$(this).toggleClass('active');
},
focusin: function() {
$(this).addClass('inside');
},
focusout: function() {
$(this).removeClass('inside');
}
});
Bonus Challenge: Have the text that appears underneath the button appear when the button is clicked and disappear if the button is clicked again
A break in our regularly scheduled program
Most everything you want to do with jQuery requires the DOM to be fully loaded.
Sometimes jQuery will try to load and hook onto elements that don't exist yet.
The browser renders the markup from top to bottom, then triggers a DOMReady event.
$(document).ready(function() {
// Handler for .ready() called.
});
This waits for the DOM to be fully loaded and does a check if it is loaded before any JavaScript/jQuery is run.
.animate( properties [, duration ] [, easing ] [, complete ] );
$('p.special').animate(
{opacity: 0.25, fontSize:'3em'},
4000,
'linear',
function(){
alert('done!');
}
);
I'm a special paragraph!
When hovering a gallery image: hide, show, or animate the overlay info.
$('.gallery li').on('mouseenter mouseleave', function() {
$(this).find('.overlay').fadeToggle('fast');
});
Add a slideshow using Slick.js!
We value your feedback and are always trying to improve.
http://bit.ly/gdi-philly-jquery
ivanaveliskova@gmail.com