On Github TNBWorkshop / jquery_101
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.
A javascript library
A collection of functions
Reusable pieces of code that do something and may return a value. Can contain other functions. (more on this later)
var p = document.createElement('p'); p.appendChild(document.createTextNode('Welcome!')); p.style.cssFloat = 'left'; p.style.styleFloat = 'left'; p.style.backgroundColor = 'red'; p.className += ' special'; var divs = document.getElementsByTagName('div'); for (var i = 0; i < divs.length; i++){ var div = divs[i]; if(/\bheader\b/.test(div.className)){ div.appendChild(p); break; } }
var p = document.createElement('p'); p.textContent = 'Welcome!'; p.style.cssFloat = 'left'; p.style.backgroundColor = 'red'; p.className += ' special'; document.querySelector('div.header').appendChild(p);
$('<p>Welcome!</p>') .css({'float': 'left', 'background-color': 'red'}) .addClass('special') .appendTo('div.header');
In your dev tools console...
$(document).ready(function() { // Handler for .ready() called. });
This HTML...
<p>Welcome!</p>
with this jQuery...
$('p').addClass('special');
results in this HTML...
<p class="special">Welcome!</p>
$('p').addClass('special');
$() Global jQuery function. Alternately "jQuery()" Used to trigger all jQuery functionality.
'p' Argument being passed into the global jQuery function. In this case, a selector to return all 'p' elements. Also accepts variables and html strings. Returns a jQuery collection/object
. We'll get back to this
addClass('') jQuery method to add the specified class to each element in the collection. http://api.jquery.com/addClass/
The $ (and jQuery), and .addClass() are just functions!
$('p')
// These are just two functions "chained" together! $('p').addClass('special');
Name(argument) function(argument)
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)
Select some elements in your sample file.
Filters create a new jQuery collection from members of an original collection that pass a check.
var collection = $('input'); var inputNotRadio = $(collection).not('[type="radio"]'); var inputError = $(collection).filter('.error'); var inputIsPA = $(collection).filter(function(){ return $(this).val() === 'PA'; });
Here is an example of passing a variable into the global jQuery function, rather than a selector.
The original collection is not altered.
$('<p>') <p></p>
$('<p class="intro">') <p class="intro"></p>
$('<p>Welcome!</p>') <p>Welcome!</p>
<a href="http://www.google.com" style="color: green;">Google</a>
$('a').html(); "Google"
$('a').attr('href'); "http://www.google.com"
$('a').css('color'); "green"
On the example page, some properties of the link to Yasmine's email.
<a href="http://www.google.com" style="color: green;">Google</a>
$('a').html('Yahoo!');
$('a').attr('href', 'http://www.yahoo.com');
$('a').css({'color': 'purple'});
Many of jQuery's methods do double-duty.
<p>What's in here?</p>
$('p').html(); // No argument, will get the value "What's in here?"
$('p').html("Heyo!"); // SETS the value!
<p>Heyo!</p>
That same set of manipulations could be written as
$('a').html('Yahoo') .attr('href','http://www.yahoo.com') .css({'color':'purple'});
because each jQuery function returns the collection again.
This is called "chaining" and is done with a period between method calls.
Chaining is a widely appreciated feature of jQuery.
$('p').addClass('special').html('hello!');
This works great when we know there is only one link.
Run $('a').append('!'); and see what happens.
We need a better selector, if we want to affect one out of many.
$('img.profile-pic').each(function(index){ if($(this).width() < $(this).height()){ $(this).css({'border':'solid 3px red'}); } else { $(this).css({'border':'solid 3px blue'}); } });
What does this function do?
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.
For all links to twitter, add an external icon to the end of the anchor content, and make the text blue.
$('a[href*="twitter"]').append('<img src="assets/externalicon.png" />') .css({'color':'blue'});
Problems with this:
Much better to apply classes than to granularly add styles and change content.
The bread and butter of jQuery.
The "click" method is one of the simplest ways to bind a handler to an event. http://api.jquery.com/click/
function onButtonClick() { console.log('clicked!'); } $('#button').click(onButtonClick);
Or more succinctly
$('#button').click(function () { console.log('clicked!'); });
You can also...
$('a').click(function (event) { event.preventDefault(); console.log('Not going there!'); });
event: 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. http://api.jquery.com/on/
$('div.test').on({ click: function() { $(this).toggleClass('active'); }, focusin: function() { $(this).addClass('inside'); }, focusout: function() { $(this).removeClass('inside'); } });
Add console.log messages on mouseEnter/mouseLeave for all names
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. });
$(function() { // Handler for .ready() called. });
.animate( properties [, duration ] [, easing ] [, complete ] );
$('p.special').animate( {height:'500',fontSize:'3em'}, 4000, 'linear', function(){ alert('done!'); } );
When clicking a profile photo, hide, show, or animate the contact info.
$('.profile-pic').on('click',function(){ $(this).siblings('.contact').slideToggle('slow'); });
Add the "sortable" functionality from jQuery UI to the nav links.
Look at GDI ajax request to meetup