On Github ivanaveliskova / gdi-jquery
Wifi — First Round Capital Guest
Password (all lowercase) — frclovesphilly
Slides — ivanaveliskova.com/gdi-jquery
Demo Files — ivanaveliskova.com/gdi-jquery/demo-files.zip
Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.
Some "rules"
Tell us about yourself.
Variables
var name = "Ivana"; var greeting = "Hey there, " + name; console.log(greeting);
Open up the demo-files/js-review in your browser and text editor to test this out!
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"] };
Functions
var name = "Ivana"; function greet() { var name = "Joey"; console.log("Hey there, " + name); } greet();
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("Molly"); sayHelloTo(); sayHelloTo(name);
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"); }
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++; }
Combining Conditionals and Looping
for(var i = 1; i <= 100; i++) { if ((i % 3) === 0 && (i % 5) === 0) { console.log("FizzBuzz"); } else if ((i % 3) === 0) { console.log("Fizz"); } else if (( i % 5) === 0) { console.log("Buzz"); } else { console.log(i); } }
Traversing the DOM
document.getElementById('presentation');
document.getElementsByClassName('slide');
document.getElementsByTagName('body');
document.querySelectorAll('a');
document.querySelector('img');
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();
$() 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
$('img').hide();
All CSS selectors are valid, plus some extras
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!
A Getter.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
.fadeIn() Gradually increases opacity of element
$('.hero img').remove(); $('#banner > span').hide(); $('#banner').children().hide(); $('img:not(.hero img)').fadeOut();
.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 after the element
$('.hero img').attr('src'); $('#banner > span').addClass('visible'); $('#banner').children().append('!');
.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"
$('a').css('color'); "green"
<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.
In demo-files/index.html, use jQuery to
Bonus Challenge! Try to change all the images in the gallery with images of your favorite celeb (or use the images in the images folder) and replace the text on the overlay!
var isMobile = screen.width <= 640; if (isMobile) { $('.desktop-nav').hide(); $('.mobile-nav').show(); }
<img class="sale-img" src="images/sale.png">
var currentTime = new Date().getTime(); // sets currentTime variable to current unix timestamp like 1428534443 if (currentTime > 1428595627) { $('.sale-img').attr('src', '/images/ends-today.png'); } // changes sale image to an 'ends today' version if the time is after 7am on Sunday
In javascript we wrote an 'if' statement and kept track of the index with a variable.
var listItems = document.getElementsByTagName('li'); for(var i = 0; i < listItems.length; i++) { console.log('This is list item # ' + i); }
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.
Use 'this' as an iterator:
$('ul li').each(function() { $(this).append('!'); });
To be more efficient, cache a variable for $(this):
$('ul li').each(function() { var $this = $(this); $this.append('!'); });
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.
$('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.
The browser renders the markup from top to bottom, then triggers a DOMReady event.
$(document).ready(function() { // Handler for .ready() called. });
Or you can put you javascript at the bottom of the document
.animate( properties [, duration ] [, easing ] [, complete ] );
$('p.special').animate( {height:'500',fontSize:'3em'}, 4000, 'linear', function(){ alert('done!'); } );
When hovering a gallery image: hide, show, or animate the overlay info.
$('.gallery li').each(function() { var $thisImage = $(this); $thisImage.on('mouseenter mouseleave', function() { $thisImage.find('.overlay').fadeToggle('fast'); }); });
http://bit.ly/gdi-philly-jquery
ivanaveliskova@gmail.com