Setup :
- Firefox
- Enough(mail me to know how much is "enough") knowledge of HTML, javascript.
- Behaviour, Prototype
- Simple ASCII editor, Notepad or Notepad++(i use it).
- 2 minutes of your valuable time to get the widget ready and 1 minute to read this scrap.
<span id="SomeId" class="SayMyName" name="Tutankhamun" />
When you place this line in your HTML, all occurences of this line will be replaced with something like :
Hello Tutankhamun!!
Ofcourse, not Tutankhamun all the time but whatever is the value for the name attribute. I will first show you the complete widget and then go into the details.
Step 1 :
Create a directory and put prototype.js, behaviour.js in it. Later save your html file and myWidget.js in it.
Step 2 :
Copy this HTML and save it as a HTML file :
<html>
<head>
<script type="text/javascript" language="javascript" src="prototype.js"></script>
<script type="text/javascript" language="javascript" src="behaviour.js"></script>
<script type="text/javascript" language="javascript" src="myWidget.js"></script>
</head>
<body>
<span id="someId" class="SayMyName" name="Tutankhamun" />
</body>
</html>
Step 3 :
Copy this javascript and save it as myWidget.js.
var myrule = {
'.SayMyName' : function(element) {
element.onclick = function() {
var helloName = element.getAttribute("name");
new Insertion.Before(element, ' Hello ' + helloName + '!!');
Element.remove(element.firstChild);
}
}
}
Behaviour.register(myrule);
Step 4 :
You are done with the widget. Open the html file in a browser and you should see :
Hello Tutankhamun!!
Details :
If you are comfortable with javascript, then it should not be very difficult to get it. Actually the main work is done by the libraries ;) behaviour and prototype. Behaviour lets you attach javascript code to html elements in a much cleaner manner. So the funda is,
- decide upon some classname which you will be using to attach a handler to. In the above example it is "SayMyName".
- Write a small rule to tell behaviour what to do if it encounters html elements with the "SayMyName" class selector.
- Since the handler is not attached to any specific event, it is fired immediately on page load(i guess so, not sure though). The handler is also passed a reference of the element which has the said classname("SayMyName").
- In the handler, get the value for the attribute "name", store it in a variable. Using the prototype library insert a new <i> element with proper text and the name that we want to echo: new Insertion.Before(element, ' Hello ' + helloName + '!!'); We no more need the span, so delete it : Element.remove(element.firstChild);
No comments:
Post a Comment