Learning AJAX: Lesson 2 - Adding A Link Using The DOM
Having made my feelings about not using AJAX before creating a site that can be used fully without it, I have moved on to the next part of my example. Previously, I had a random quote generator that displayed a different quote when you refreshed the page. My aim is to use AJAX techniques to enable you to display a new quote without refreshing the page, but by clicking a link instead. To do so we will need to do some DOM scripting.
The Markup Doesn't Change
Currently, the example does not have a link to click to replace the quote with a new one. We could add one into the markup so that it could trigger our javascript function that we are still to write, but if a user without javascript enabled visited our page then there would be a useless, broken link. From here on in, the markup for the page will stay the same and everything is to be added dynamically by javascript.
The addJSLink Function
I created a function called
addJSLink(elementID,onClickFunction,linkText)
which takes three parameters:
- elementID
- The ID of the element we want to add the link to.
- onClickFunction
- The function we want the added link to perform.
- linkText
- The text for the link.
Take a look at the commented code and see what I have done. I didn't have to use the parameters, I could have built the options straight into the function, but this script is more useful this way. Why? It can be used to add any link, any onClick function and any link text you want. Feel free to do so!
addJSLink In Action
I suppose I told a small lie when I said I wasn't going to change the markup at all. The only change I have made to the original example has been to add the link to the javascript to the head of the page, nothing else has changed. So check out the random quote generator with added javascript link and keep an eye out for the next part of this series.