All posts tagged Javascript

Good Ways to Implement Javascript on your site

Everyone likes to ‘jazz’ up their website, if done correctly it can add much to the user’s experience and with libraries such as jQuery so incredibly easy to use and integrate into a website it is becoming more popular all the time. However, there can be an over reliance on Javascript and this article will look at when to use Javascript, some ideas on what to implement using it and discuss fall-back options.

Why even Bother?

Why should we even worry about when and when not to use Javascript? It’s because, unlike server side languages like PHP, Javascript is client side, which means the user can turn Javascript off if they prefer. So you can never know if a user on your website has Javascript turned on or not. So anything that is vital on your website cannot be done purely in Javascript. Note that I say ”purely’. It’s very popular these days to provide an all singing, all dancing solution for those with javascript on, but give those without it a very usable solution.

When you can use it.

We all want to know when we can use it – after all it can really add an extra dimension to your websites!

Form Assistance

jQuery can be used in a number of ways to assist users when filling out forms. We all know that if forms are a pain, people just will often not bother but with the assistance of javascript we can add some important features such as:

  • Immediate Validation – here the data can be validated as the user types it, meaning they are immediately informed of any mistakes.
  • Pop Up Assistance – a popular edition to forms, when a user clicks to type in a certain field a small box fades into view with some helpful advice.
  • Ajax Submission – using AJAX the user can submit the form without having to reload the page.

Modal Windows

Modal windows are fantastic for a number of reasons. They are typically used for image galleries – we’ve all seen the popular “Lightbox” in action and it provides a nice effect. They can also be used to notify users – error messages for example, being placed in the centre of the screen and not going away until a button is clicked is a sure fire way to get the user’s attention.

  • Light Box – there are a number of popular ways to do this online, both with plain old javascript and also with libraries such as jQuery and Mootools. This is a very popular effect as I mentioned – and the great thing is if the user does not have javascript turned on they don’t lose any essential features.
  • Error/Warning Messages – again very easy to use and implement and great to get the user’s attention. Of course you need to make sure if javascript is turned off the message is still shown.

Content Rotators

Javascript can be used to rotate through a number of items very easily and a fall-back for those without javascript is also pretty easy to implement.

  • Image Rotators – a superb way to display a number of images whilst saving space as images as just rotated round one after the other. It also means the image may be different every time a user visits which is a nice effect also. For users without javascript I tend to use PHP to randomly display an image when the page loads, but that’s as far as you can really go.
  • Content rotators – a great example can be found here on John O’Nolan’s blog. Essentially the same set up as a image rotator and it is a fantastic addition to a site, allowing the user to browse a selection of content easily and quickly.
  • Any Others?

    If you’ve got any more ideas feel free to post them in the comments and I’ll hopefully do a follow up article soon.

    Hola Mundo – An Intro to Javascript

    All real-world languages have many ways of saying the same thing– Hiya doin, Hello, What’s up? The same is true of the programming language JavaScript. Let’s look at different ways of saying “hello world” as a way of learning to code with JavaScript.

    Open up a new plain text file in Notepad, and paste or type the following HTML page content into it:

    <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;>
    <html>
      <head>
        <meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=utf-8&quot;>
        <title></title>
        <script type=&quot;text/javascript&quot;>
          function sayHello (){
            alert (&quot;hola mundo!&quot;)
          }
          function sayHello2 (){
            var s = prompt(&quot;Enter your name:&quot;, &quot;John Q. Public&quot;);
            alert (&quot;hola mundo! and &quot; + s);
          }
          function sayHello3 (){
            // This is a callback for the keyup event on a text box
            // it dynamically updates a heading1 in the document with the text box's value
            var src = document.getElementById(&quot;obSource&quot;);
            var out = document.getElementById(&quot;idHeading&quot;);
            out.childNodes[0].data = src.value;
          }
        </script>
      </head>
      <body>
        <div>
          <input type=&quot;button&quot;  value=&quot;click me&quot; onclick=&quot;sayHello();&quot; >
          <P>&amp;nbsp;</P>
          <hr>
          <input type=&quot;button&quot;  value=&quot;click me&quot; onclick=&quot;sayHello2();&quot; >
          <P>&amp;nbsp;</P>
          <hr>
          <input type=&quot;text&quot; id=&quot;obSource&quot; value=&quot;type something&quot; onkeyup=&quot;sayHello3();&quot; >
          <P>&amp;nbsp;</P>
        </div>
        <div>
          <hr>
          <h1 style=&quot;font-family:verdana&quot; id=&quot;idHeading&quot;>A Sample Heading</h1>
        </div>
        <hr>
      </body>
    </html>
    

    Save the page to your desktop as “holaMundo.htm,” and double-click it to load it into your browser. Press the first button to make the greeting appear.

    The first button: an output statement

    Focus on just this portion of the code:

    function sayHello (){
      alert ("hola mundo!")
    }
    

    It’s pretty clear, even if you have no programming experience, which statement is actually outputting the message: the alert statement. But what’s the other stuff surrounding that statement?

    The function statement wraps the alert function in a code block that makes it easy to chunk up a big program. You can think of functions as being like the chapters of a good novel: they break up the action into mini stories that make it easy for the reader to read the whole story.

    We could put more program code before or after the alert statement, but don’t need to if we just want to illustrate how the alert statement works. Other functions in our example code do hold several statements.

    The second button: an input statement

    Reload the example page in your browser and press the second button this time. Respond to the prompt, press OK, and watch the new message appear.

    Let’s study just this much of the main program:

    function sayHello2 (){
      var s = prompt("Enter your name:", "John Q. Public");
      alert ("hola mundo! and " + s);
    }
    

    The prompt statement takes in text from the user of your JavaScript program. The first _parameter_ is the message to give the user, and the second is the text that the prompt statement will return with if the user enters no text.

    JavaScript variables

    Notice the program code to the left of the prompt statement: “var s =”. This code creates a variable–space from your computer’s memory–to hold the text that the prompt statement gets from the user. There are different kinds of variables for different data types: some variables hold string values, e.g. “hola!” while others hold numeric values e.g. 3.1415927, 77.

    JavaScript programming can be a bit frustrating at times because, no matter what type of data a variable is holding, all variables are declared with just the “var” keyword. Compare this with Java programming, where you tell the compiler the specific type of data that a variable holds, for example:

    • int a;
    • String s;

    The plus operator

    Notice the line after the prompt statement. It’s an alert statement with a plus operator inside it. The plus operator joins two strings together: the literal string “Enter your name,” and the string held in the variable s. Think of one string being added to another, as on number is added to another, and the plus operator will make sense to you.

    The text box

    Reload the sample program in your browser and enter some text in the text box. Notice that the headline echoes the text you enter with each keystroke.

    Focus on just the third function in your program:

    function sayHello3 (){
      // This will be a callback for the key up event on a text box
      // It dynamically updates a heading1 in the document with the text box's value
      var src = document.getElementById("obSource");
      var out = document.getElementById("idHeading");
      out.childNodes[0].data = src.value;
    }
    

    How “sayHello3″ works

    The first two statements are declaring and making assignments to variables. Two _object references_ are stored in the variables. The objects represent elements of the HTML page. One object is the text box that you type into:

    <input type=&quot;text&quot; id=&quot;obSource&quot; value=&quot;type something&quot; onkeyup=&quot;sayHello3();&quot; >

    Notice the id _attribute_ for this element: “obSource.” This attribute value is the name that the program code in sayHello3 uses to access the text in the text box. This functionality is just like calling someone on the phone: you can’t call a particular person unless you have her phone number. The id attribute is like the phone number we use to “call” or get access to the text box element.

    In the same way, the “var out” statement gets a reference to the destination object to receive the user-input text.

    The script’s data structure: a tree

    The last statement in sayHello3 copies the source text to the destination. Although this statement looks a bit cryptic, it will make a lot more sense if you see the data structure being used here: it’s a tree, whose leaves are referred to as “nodes.”

    We’ve talked about the _what_ of the program but have missed the _when_ so far. It’s pretty striking that the page’s heading changes dynamically with each keystroke in the text box. How does the program code make that happen?

    When the sayHello functions are called: events

    The answer is events, and subscribing to, or listening to those events. The event that concerns this example program is the keyup event on the text box control. When that event happens, the browser calls the sayHello3 function.

    How does the browser know which function to call? The HTML markup tells it:

    <input type=&quot;text&quot; id=&quot;obSource&quot; value=&quot;type something&quot; onkeyup=&quot;sayHello3();&quot; >

    The key attribute here is “onkeyup.” Look at what’s assigned to it: sayHello3. That assignment tells the browser to call sayHello3 when a key up event happens to or on the text box.

    Approaches to Learning JavaScript

    Two of the best ways of learning how to code in JavaScript are these: tinker with and take apart existing working scripts, and memorizing and recreating a working script without consulting resources beyond your gray matter.

    Continue your JavaScript learning journey by tinkering with the code in this tutorial.

    References

    JavaScript Core Reference: http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.5/reference/contents.html

    Clean Up Your Page, Removing Bad Behaviour

    Cliché, cliché, cliché… What old analogy can I use to sum up this little tutorial? I think I’ve decided on one.

    Would you wear walking, speak T-shirts or skull around all day? I think not. Actually, I will make a fairly confident statement and say that your eyebrows made a slight movement towards the ceiling while reading those questions, or at the very least you attempted to put on a pair of walking or got up and tried to skull around.

    As cryptic as the analogy is, it makes perfect sense for this tutorial. You do not want to mix behaviour with your presentation. You want to wear something designed for the task like a T-Shirt. You do not want your behaviour jumping in amongst your structure either; we do not have a pirouette bone in our body because this behaviour is not part of our structure. Our structure, presentation and behaviour all work together but are separate parts of us as a whole.

    Would you wear walking, speak T-shirts or skull around all day? I think not. Actually, I will make a fairly confident statement and say that your eyebrows made a slight movement towards the ceiling while reading those questions, or at the very least you attempted to put on a pair of walking or got up and tried to skull around.

    As cryptic as the analogy is, it makes perfect sense for this tutorial. You do not want to mix behaviour with your presentation. You want to wear something designed for the task like a T-Shirt. You do not want your behaviour jumping in amongst your structure either; we do not have a pirouette bone in our body because this behaviour is not part of our structure. Our structure, presentation and behaviour all work together but are separate parts of us as a whole.

    I know, I know… I have not told you what it is this tutorial is about yet and judging by your general restlessness and tooth grinding, you are dying to find out. Well, I have always been terrible at keeping secrets so I will spill the beans.

    Separating Behaviour (JavaScript) From Structure and Presentation

    As frustrating as it can sometimes be to code your websites to comply with some of the recommendations and specifications set down by the World Wide Web Consortium (W3), these standards do have your best interests at heart. Sure, it may take a little longer to learn the correct way and in some cases it may take a little longer to write the mark-up but their recommendations really do make things easier, not only for you, but also for your users.

    If you are like me and learned HTML before anything else in the WWW, you would probably have spent a large amount of time learning to use the archaic HTML presentational elements to create your pages. Something as simple as a colourful paragraph would require ludicrous overuse of tags and color=”" attributes. HTML was suffering badly, my website source-code was a sickening tag soup and the humble HTML, a procedural, structural, mark-up language was being asked to do much more than it was designed to do.

    My battle – and the long-suffering HTML’s battle– with these elements ended when I discovering the heroic Cascading Style Sheet. What was so special about CSS that it was able to make my life as a web designer that much easier? It took the presentation of web documents and separated it from the structure. No longer was it necessary to fiddle about inside ridiculous numbers of presentational tags to get the look and feel required by my creative mind. I was able to shift the presentation to a document and format designed exactly for the cause and in doing so I was able to relieve the burden placed on the structure of my pages.

    It did not take long for the benefits of CSS to become clear — portable, abstracted presentation allowing for site-wide layout modifications by changing a single file.

    It was not perfect though; there are three aspects to a website — structure, presentation and behaviour. CSS had taken the presentation out of the equation but my HTML was left littered with behavioural modifiers. My growing skills with Dynamic HTML gave me motivation to enhance my pages but the gap left by presentational code I had moved to CSS was quickly filling with behavioural JavaScript code. This last bit of separation anxiety was extinguished when I became aware of yet another W3 recommendation, The Document Object Model, giving me a way to isolate behaviour leaving HTML to do what it is best at, structuring content.

    The Document Object Model

    So what is the Document Object Model (DOM) and what tricks does it bring to the party that earns it such following of eager young lasses web designers?

    The DOM is an Application Programming Interface designed to access and manipulate objects contained within documents of a hierarchal nature… What is that you say? You just want to mess about with a web page not start flipping around in hierarchy nonsense?

    Well that is the thing. The DOM gives client side developers a way to reach any element in a (x)HTML page from an abstracted layer outside of the structure. In the same way as CSS removed website presentation from the HTML structure, the DOM removes website behaviour from the structure. From a specialised document, you can control the behaviour of a webpage and finally leave HTML to control the structure – the job HTML was created to perform.

    Strictly coded HTML and xHTML implements a logical structure and has a hierarchy whereby every element has a parent element all the way up to the root element – the element is the root of every HTML page. So using this HTML family tree, you can traverse your way to any element simply by looking down through the generations of children. The first

    element of your web page would be the great-grandchild of the element.

     -->  -->
    

    Okay, so you can see now that it is possible to drill your way down to any element you desire, let’s start having a look at what problems the DOM solves and some of the methods available for us to achieve them.

    JavaScript, unbelievably, is a very powerful Object Oriented language that allows many of the OOP philosophies to be brought across to client side coding. The major philosophy here is abstraction – moving the behavioural logic into a layer above the structure and presentation.

    The examples below will all be manipulating one simple HTML document from an external .js file. The HTML document follows – you may use any HTML page for these examples as the code can simply be attached to another page, nothing is hard-coded into the HTML structure.

    Please take the time to read the points described in the HTML file to understand the benefits of coding with the DOM.

    As discussed above, the root or top-level parent of a HTML document is the tag. The JavaScript keyword document can be considered “The ” tag for purposes of understanding the correct hierarchy. Just about all of the DOM traversing methods available for document can be used on more specific child elements as well.

    www.lukedingle.com/scripts/dom.php is where you can see and download the HTML. Note that this page is just a normal functioning HTML page. There will be no changes made to the HTML at all.

    Traversing the DOM

    Accessing a Single Element

    Something that you will want to do again and in your JavaScript’s is isolate a single element on your page and perform some sort of action with it. It could be any element, and you can perform any JavaScript actions on it. The easiest and most direct method to do this is with getElementById.

    The getElementById method takes a single string as its argument. This string is the id=”" attribute of a HTML element. If the given string matches an id attribute within the document, the function will return a reference to that element. If it does not match, this function will return null.

    Let’s have a look at an example usage. The following code will get a reference to the #header div in our document. It will then change the background colour when the user moves their mouse over the div.

    // This function will be added to throughout the tutorial
    // This function will be run when the a page loads and will set up
    // The various things using the DOM
    
    var backgroundColour = '#EEEEEE'; // This is the colour the background will turn on mouseover
    var date = new Date();		 // a date object to use later
    var infoDiv = 'border';			 // This is the div we will be adding text to later
    var externalFlag = 'external';   // The class name given to links to external sites
    
    var message      = 'Oh! Please don\'t leave so soon! By clicking okay, you will go to another site. Are you sure you want to?'; // Message on leaving
    
    function initiatePage ()
    {
    	// Let's get a reference to the #header div in our document.
    	var header = document.getElementById('header');
    
    	// Now, we'll attach the background colour changing function
    	// to the header div's onmouseover and onmouseout event handlers
    
    	header.onmouseover = changeBackground;
    	header.onmouseout  = changeBackground;
    }
    
    function changeBackground()
    {
    	if (this.style.backgroundColor == '')
    	{
    		this.style.backgroundColor = backgroundColour;
    	} else {
    		this.style.backgroundColor = '';
    	}
    }
    
    // Attach the initiatePage function to the onload event handler of the window object
    window.onload = initiatePage;

    See results at : www.lukedingle.com/scripts/dom.php?getCode

    Pretty simple hey? Without a single line of code in the HTML page we are able to eliminate an onmouseover=”" onmouseout=”" and perhaps even a tag to declare the function.

    A few things to note from the preceding code that may seem a little different to what you’re used to.

    • Once you have a reference to a HTML node stored in a variable, you can treat it like any other JavaScript object. This includes adding custom properties and methods. You just get the benefit of having all the default properties and methods for the type of element.
    • You can assign a function to a method in two ways. You can define a function and add it using the function name (note that you don’t use parentheses as this will execute the function) or you can add it as an inline function declaration.
      var.method = function () { /* function code here */};
    • When you are creating functions to be assigned to objects, you can use the this special variable. The this variable can basically be replaced with “The object that this function is attached to”. It gives you a way of attaching the same function to as many objects as you desire without having to worry about variable names.