Prototype Tutorial Hello World Example



Before we can write our first Prototpe Hello world example, we will have to first download a the file called prototype.js from the site http://www.prototypejs.org/download. The latest version at the time of writing is 1.7.1

Save file


You can save the file on your server in the same directory as your current html file, but it is better if you save in a subdirectory prototype. You will have to specify your source accordingly.

Your first prototype code


Let us now move on to our first prototype code.



<html>
<head>
<title>Prototype examples</title>
   <script type="text/javascript"  src="../javascript/prototype.js"></script>
<script>
   function test()
  {
   $("firstDiv").update("New Text - Hello World")
   }
</script>

</head>
<body>
   <div id="firstDiv">
      <p>Welcome to ReferenceDesigner.com prototype Tutorial</p> 
   </div>

   <input type="button" value="Test $()" onclick="test();"/>

</body>
</html>



You may like to try this example here.



Explanation



We include the prototype include file using


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




We assume that the file prototype.js is in the subirectory javascript. It is also possible to keep the prototype.js in the same directory, in which case, this statement looks like


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




The test function is used to change the text inside a div element firstDiv. This is where the prototype.js comes into play. The update() is a prototype function. Basically every prototype acts by selecting an element and doing some action on it. Using $("firstDiv") , we select an element inside the html and using the update() function we make changes. More of it will be clear in a while


 function test()
  {
   $("firstDiv").update("New Text - Hello World")
   }




Inside the HTML we define a div element with id firstDiv. It is this id with which we select a particular element that we manipulate.


 <div id="firstDiv">
      <p>Welcome to ReferenceDesigner.com prototype Tutorial</p> 
   </div>




And finally we define a button, that will do some action ( call the function test() )

  <input type="button" value="Test $()" onclick="test();"/>




We hope that it makes a lot of things clear. You may want to try following simple exerciseto strengthen your understanding of the prototype.

Exercise 1: Change the text that is printed on clicking the button.

Exercise 2: Define two div elements. Your code should have change only one div element on changing the paragraph.

Exercise 3: Define two div elements and two buttons. On clicking first button the first div element changes and on clicking second button, the second div element changes.

Try to give your best to do the exercises. Here are the solutions

Solution - Exercise 1.
Solution - Exercise 2.
Solution - Exercise 3.