JavaScript:jQuery

From Progzoo
Revision as of 10:42, 2 January 2013 by Andr3w (Talk | contribs) (Programming some content)

Jump to: navigation, search

Introduction to jQuery and JavaScript

Hello World

Create two files yourself; q1.html and q1.js – these have the following content:

q1.htmlq1.js
<!doctype html>
<script src="jquery.min.js"></script>
<script src="q1.js"></script>
<body>
</body>
$(function(){
  alert('Hello World');
});

Hello jQuery.png

Download the jQuery file from http://jquery.com and save it in the same directory. Load q1.html into a web browser:

Adding Content

The $ function is called once the main page elements are loaded. You can build content in the ready function or you can examine the existing page when ready:

$(function(){
  $('body').append("Here is a button:");
  $('body').append($('<button/>',{text:'Click me'}));
});

You can make your button do something:

$(function(){
  $('body').append("Here is a button:");
  $('body').append($('<button/>',{text:'Click me',
    click:function(){
      alert('Hello World');
    }}));
});


Programming some content

The following example creates some words and images. You can get the gif images from http://progzoo.net/flags.zip

var cl = [
   {name:'Brazil',src:'br.gif'},
   {name:'France',src:'fr.gif'},
   {name:'Greece',src:'gr.gif'},
   {name:'Italy', src:'it.gif'},
   {name:'South Africa',src:'za.gif'}
   ];
$(function(){
  for(var i=0;i<cl.length;i++){
    $('body').append(cl[i].name);
    $('body').append($('<img/>',{src:cl[i].src}));
  }
});	 

Q3 jQuery.png

You can add style to the elements (see question 4 for how to do this). The name of each country has been put in a div. The div has the fontSize set to 200% The div has topMargin set to 2em

The images have an 8px gray border.


In this example each country has a div that floats left. Inside each div is another div with the country name and an image for the flag. The flag height has been set to 100px The outer div has a margin of 1em a background color of #BBB and a fixed with of 220px.

Note that the flags.zip file contains cl.json – you can use this to show hundreds of flags.