2. What can I use it for?
• Add/remove/modify content
• Set CSS styles, add/remove classes
• Show/hide/animate parts of the page
• React to events (clicks, typing, etc.)
• And much, much more!
3. Basic Concept -
Comments
// this line doesn't do anything!
/* These series of lines
is a bit longer but it
also doesn't do anything! */
$('a').hide(); // hide 'a'
$('a').hide(); // hide all links
$('a').hide(); // hide links while we validate them
4. Basic Concept -
Variables
var classes = 'products rocks monkeys';
var num = 2;
classes = classes + ' another';
// now: products rocks monkeys another
num = num * 2;
// now: 4
5. Basic Concept -
Functions
// assigning a function to a variable
// so we can call it several times
var test = function(message, count) {
count = count * 2;
console.log(message, count);
};
test('hello!', 1);
test('hello again!', 2);
// using a function to delay work
$(document).ready(
function() {
alert('document is ready!');
}
);
6. Basic Concept - Scope
var test = function(message, count) {
poorForm = 'probably a mistake';
var test = 1;
console.log(message, count, test, poorForm);
};
test('hello!', 1);
7. Basic Concept - jQuery
// locate zero or more things on the page:
$('css selector');
// do something with them
$('css selector').method();
e.g.
$('a') // gets all links
$('a.prods') // gets all links with prods class
$('a').hide(); // hide all links
$('a.prods').hide(); // hide links with prods class
$('a.misses').hide(); // no matches? no worries!
8. Getting setup to run JS
• Include jQuery on the page
<script src="http://ajax.googleapis.com/ajax/libs/
jquery/1.9.0/jquery.min.js" type="text/javascript"></
script>
9. Getting setup to run JS
• Add a script block to your page
<script type="text/javascript">
$(document).ready(function() {
/* my fancy JS code goes here! */
});
</script>
10. Simple JS Example
• Lets turn all links on the page green
<script type="text/javascript">
$(document).ready(function() {
$('a').css('color', 'green');
});
</script>
11. Interactive JS Example
• Lets hide links when they are clicked
<script type="text/javascript">
$(document).ready(function() {
$('a').css('color', 'green');
$('a').click(function() {
$(this).fadeOut();
return false;
});
});
</script>
12. Do I need to use
jQuery?
• No! But a JavaScript framework sure helps.
• Cross-Browser Issues
• More compact code
13. Example Fade Out
• Plain JS
<script type="text/javascript">
document.addEventListener(
'DOMContentLoaded',
function(){
var s = document.getElementById('thing').style;
s.opacity = 1;
var fade = function(){
s.opacity = s.opacity - 0.1;
if (s.opacity < 0) {
s.display = "none";
} else {
setTimeout(fade, 40);
}
};
fade();
}
);
</script>
14. Example Fade Out
• jQuery
<script src="http://ajax.googleapis.com/ajax/libs/
jquery/1.9.0/jquery.min.js" type="text/javascript"></
script>
<script type="text/javascript">
$(document).ready(function() {
$('#thing').fadeOut();
});
</script>