Courses/Design & Technique-Essential Web Design/Q2/03
jQuery
What is jQuery
jQuery is a JavaScript library makes programming in JS a lot simpler and a lot less messy.
There are many JavaScript libraries, that make certain aspects of programming in JS easier - e.g. working with SVG, maps, making visualizations, etc, etc.
jQuery is on of the most popular and general purpose JavaScript libraries
JS, made easy
Like with JS you can use jQuery to:
- change HTML content
- change element attributes
- change an element style
- retrieve the window size
- listen to an even (e.g. a mouse click)
- make a timer
- validate data
But jquery makes your life to much easier, let's see how!
Basic: loading jQuery library
jQuery is simply an external JavaScript file that you load on to your HTML page.
There are different ways to load it, inside the HTML <head></head> with::
- Download the jQuery file (latest version & compressed, production)from http://jquery.com/download/ and loading it:
<head>
<script src="jquery-1.11.3.min.js"></script>
</head>
- Load it from online resource (CDN)
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
Basic: loading code
Once you loaded the jQuery library (file), you need to load your jQuery code.
the most secure way, that ensures the code is run only after all the contents from the page are loaded is:
<script>
$(document).ready(
function(){
//your jQuery/JS code goes here
})
</script>
Basic: jQuery syntax - selectors
In order to change or retrieve HTML elements' content, attributes, style, we need to select those element(s) precisely. jQuery is master in those selection.
simple selectors
- element selector:
$('h1')
will select all the heading1 elements. - id selector:
$('#large')
will select the element with id large. - class selector:
$('.small')
will select all the elements with class small.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1>I am a h1</h1>
<p id="large">I am p#large and will become large</p>
<p class="rotate">I am p.rotate and will tilt</p>
<h2 class="rotate">I am a h2.rotate and even I will shift position</h2>
<script>
$(document).ready(
function(){
alert("be alert for the changes in the elements' text and CSS");
$('h1').text('Yes, your a h1');
$('#large').css('font-size', '50pt');
$('.rotate').css('transform', 'skew(0deg, 5deg)');
})
</script>
</body>
</html>
advanced selectors
- Descendent selectors:
$('ul a')
will select all a tags inside the ul tags. - Child selectors:
$('ul li')
will select all li tags that are direct children from the ul tags. - Attribute selectors:
$('img[src="img.jpg"]')
will select all imgs that have as src the image img.jpg.
Jquery classes??
- change HTML content - .text() ??
- change element attributes - .attr()
- change an element style - .css()
- retrieve the window size - window.attr('width'
- listen to an even (e.g. a mouse click) $('body').click()