This website stores cookies. Click here to accept them.cookie information page

"javascript" category

More on jQuery

3rd February 2012
Categories: javascript, jquery

Javascript, the main language that enables dynamic websites, has been around for 15 years and, whilst powerful (it enables client-side form validation and dynamic pages, it is used for google analytics and various other trackers and is used by most modern websites for one thing or another) has generally been annoying to use. Every browser has had it's own implementation of javascript, with it's own idea's of how things should be done, this lead to lots of logical statements to handle all the different browser designs:

 

if (document.layers)

{

var container = document.layers[ID].open();

container.write(“some text”)

container.close();

}

else if (parseInt(navigator.appVersion) >=5 &&navigator.appName==”Netscape”)

{

document.getElementById(ID).innerHTML = “some text”);

}

else if (document.all)

{

document.all[ID].innerHTML = “some text”

}

 

All these codeblocks do the same thing, writing the text “some text” into a specified HTML element, the only difference is browser compatiblity. The first block works in Netscape4, the second block in Netscape 5+ and the last block works in Internet Explorer 4,5,6. If you wanted to look at this script in any other browser then you would just have to hope that it worked.

That's a lot of lines of code for something so simple, writing a more complex script would end up as a nightmare of if statements. Fortunately for the best part of the new millenium a number of javascript libraries have been released, one of the most prolific of these is JQuery. Released in 2006 it is now, according to wikipedia, used by over 52% of the 10,000 most visited sites and is the most popular library currently in use. Jquery is available from http://www.jquery.com

JQuery provides a number of useful functions that simplify interacting with the webpage and handle all the nasty cross-browser compatibility issues for you. All of Jquery's functionality is provided by the jQuery() object ( or it's alias “$()” ) and most JQuery scripts will start off with a document-ready block. This is a callback passed to the ready function of the document object that is called when the page has finished loading. So, let's rewrite our previous script using JQuery:

/blogresources/jquery-hello-world.html

 

So, this script (which also contains a method to trigger it, unlike the previous example) is only 3 lines of javascript (always nice to do more with less) and, although it can look a bit daunting at first, it is a relatively simple script. It starts off with the document-ready block that I mentioned earlier. This involves creating a JQuery object that contains the document ( $(document) ), which we then call the ready function on passing it a closure (an inline function). When this function is executed (after page load), we select the DOM element that has an id of 'click-me' and call the click method. This function allows us to bind a callback, a function that will be executed whenever the target is clicked, in this instance our function (with ONE line of code) sets the HTML contents of an element to “Hello World”. Easy.

Now I should probably take a minute to reveal the wonders of the JQuery constructor. A Jquery object can hold multiple DOM objects and there are three ways of constructing them:

  • The first (and in my experience, most common) is to use a CSS type selector ('# for id, . for class etc) passed in as a string (much like we did above with the “#click-me” and “#jquery_target” selectors.

  • The second is to pass in a DOM object (like we did with the “document” constructor above) .

  • The third is to pass in a string containing HTML (for instance $('<p class=”some-text”>some paragraph content</p>') ).

One important thing to remember is that functions that change the object(s) will generally be applied to every DOM element contained by the JQuery object, whilst functions that retrieve data will generally read the data from the first element in the JQuery object. This means that, for example, if we wished to stop any of the links in our page (or a part of our page) from working (or send an ajax notification or whatever) we could do something like the following:

 /blogresources/jquery-link-selection.html 

This script, again, is very simple. Once again we have our document-ready block, this time we are binding an on-click callback to a collection of DOM elements (every A tag within the element that has an id of “link-container”). This callback retrieves the href attribute of the clicked tag and displays it in the jquery_target box at the bottom of the page. It then returns false (this is to prevent the browser from then following the link)

So thats JQuery in a nutshell. A small, yet powerful library that enables developers to write stunning web-apps and add that little bit of shine to a website that makes visitors want to come back.  

A short introduction to Ajax

11th January 2012
Categories: ajax, basics, javascript

Web pages are old. HTTP (the protocol that browsers use to retrieve pages) has been around since the early 90's and was originally designed as a simple request/response mechanism. Unfortunately this means that any time a page needs updating, the whole thing has to be re-downloaded from the server which can be slow, tiresome and leads to annoying screen repaints. Enter AJAX (Asynchronous Javascript and XML), a methodology developed in the late 90's that allows javascript to request data from the server, this allows developer's to write cleaner, nicer and more helpful user interfaces.

Hello World

It's a tradition that your first steps in a new language should be a hello world type application/script. So without further ado here comes an Ajax Hello World Script (note, for this tutorial I'm going to be using JQuery, available from http://www.jquery.com).

If you want to skip to the result, click here.

 <!DOCTYPE html>
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>AJAX Hello World</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function()

{

  $('#ajaxButton').click(function()

  {

    $.get('http://www.oxford-web.co.uk/blogresources/ajax-hello-world.php', function(data)

    {

      $('#ajax_target').html(data);

    });

  });

});

</script>

</head>
<body>

<div>
<div style="background-color:#373639">

<img src="http://www.oxford-web.co.uk/app/images/structure2011/logobanner-transparent.png" title="Oxford Web">

</div>

<div style="padding:24px">

  This is part of a blog post from the <a href="http://www.oxford-web.co.uk"   target="_blank">www.oxford-web.co.uk</a> site.

   <button id="ajaxButton">Click Me</button>

  </div>

  <div id="ajax_target" style="background:#c0c0c0;padding:24px">

  </div>

 </div>

</body>

</html>

The first thing we do (outside of the basic HTML template) is to include JQuery (<script ... ”jquery.js”>). We can then move on to requesting data from the server. JQuery, by default, uses the $ symbol as a shortcut to the JQuery object. In this example we are using the 'get' function (there is also a 'post' function for HTTP POST requests which works in exactly the same way), to which we pass a url and a callback that gets executed when the request is complete.

Using Parameters

Now this is fairly nice stuff but obviously we want to be able to give the server a bit more information. Now we could manually build up a GET uri (append ?field=val&field=val...) but this can get tedious and untidy, not to mention it doesn't help us much with POST requests. Fortunately JQuery can handle the tedious parts for you, just pass it a JSON object (JSON, Javascript Object Notation) and the fields will be used as request parameters.

<!DOCTYPE html>

<html>

<head>

<META http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>AJAX Hello Name</title>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

$(document).ready(function()

{

  $('#ajaxButton').click(function()

  {

    $.get('http://www.oxford-web.co.uk/blogresources/ajax-hello-world.php',

    {

      name: $('#name').val()

    },

   function(data)

   {

   $('#ajax_target').html(data);

   });

  });

});

</script>

</head>

<body>

<div>

<div style="background-color:#373639">

<img src="http://www.oxford-web.co.uk/app/images/structure2011/logobanner-transparent.png" title="Oxford Web">

</div>

 

<div style="padding:24px">

<p>This is part of a blog post from the <a href="http://www.oxford-web.co.uk" target="_blank">www.oxford-web.co.uk</a> site.</p>

<p>type something in the box and click go to refresh just the shaded part of the screen...</p>

<input type="text" id="name" /><br/>

<button id="ajaxButton">Click Me</button>

</div>

<div id="ajax_target" style="background:#c0c0c0;padding:24px">

</div>

</div>

</body>

</html>

 

The above returns the same as typing http://www.oxford-web.co.uk/blogresources/ajax-hello-world.php?name=danny.

Conclusion

So there we have it - a simple, basic introduction to the wonders of Ajax that allows web pages to become dynamic, auto-completing, auto-updating web applications.

What is jQuery?

21st December 2011
Categories: basics, javascript

I'm building a shed in my garden. What I need is to put bikes, a lawnmower, a few tins of paint, a toolbox and some random junk under cover. That's the primary aim of the project.  The seconday aim is that it mustn't look too shabby.  And finally it mustn't be a lot of work to put up.

Now I know that the raw materials for building a shed are wood and nails, and maybe some glue. But it would be great if some of the pieces of wood came stuck together already, so that I didn't have to do so much hard work to achieve my goals.

Enter the pre-fabricated shed, and ta-da!  It takes less than half the time.

jQuery is basically a pre-fab shed for Javascript. Someone has spent a lot of time and energy building commonly-used routines and functions to do things like showing and hiding bits of web page, calendar controls, and that kind of thing, and once you have jQuery and some simple documentation you can access them very easily without all the hard work.

Take 'lightboxes' for example. They are a popup window in the middle of your web page to show an image. They can be part of a gallery and include 'previous' and 'next buttons'.

If you google 'jQuery lightbox' you'll get an example of this javascript at work, and a download link which gives you the jQuery core library and the lightbox library, and some sample code to get you started with your very own lightbox code.

The way a lot of jQuery works is by modifying attributes of existing HTML.  Say you have some HTML which looks like this:

<div class="someclass">
<ul>
   <li>
     <a title="Some random picture" href="pic.jpg">
        <img src="thumb.jpg">
      </a>
    </li>
</ul>
</div> 

The jQuery code for turning your thumbnail picture into a link to a lightbox happens in the Javascript at the top of the page, where you call a function to modify the action of the anchor tag.  Most of the work that's done is hidden from you (the coder), you simply call a jQuery function to turn  the div into a lightbox gallery.

© Alberon Ltd 2018

8 Standingford House
26 Cave Street
Oxford
OX4 1BA

01865 596 144

Oxford Web is a trading name of Alberon Ltd, registered company no. 5765707 (England & Wales).