SilabGarza - RS Private Server  
Home Forum Play Register Store Market Highscores Mark Forums Read
Go Back   SilabGarza - RS Private Server > SilGar Media > Computers > Programming
Reload this Page Javascript and the DOM


Javascript and the DOM
Old
  (#1 (permalink))
Evolution is Offline
Also known as Anthony`
image
 
Evolution's Avatar
 
Posts: 43
Cookies Given: 0
Cookies Received: 0
Time Online: 2 h 50 m
   
Lightbulb Javascript and the DOM - 08-29-2010, 11:24 AM

Hello, in this tutorial im going to be covering how to manipulate your web page using Javascript and a powerful mechanism called the Document Object Model. The contents of your webpage are available through the DOM, and can be manipulated and changed. In this tutorial we will be manipulating the DOM with Javascript.

This tutorial will not teach the basics of Javascript, if you would like a tutorial on learning Javascript I recommend,
http://w3schools.com/js/default.asp

The DOM has a special set of variables and objects that represent different aspects of the webpage such as content, location, status and many more.




Common DOM Objects
  • document - Represents the (X)HTML page
  • location - Represents the current URL
  • status - Represents the browser's status bar
  • history - Represents the browser's history
  • navigator - Represents information about the browser
You can find all DOM objects on this page,
http://www.w3schools.com/jsref/obj_window.asp


You can allow Javascript to manipulate the DOM. We are going to start with a simple example of changing the style of a page;
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Simple DOM Manipulation</title>
    </head>
    <body>
        <h1>Wat u want foo</h1>
        <script type="text/javascript">
            // Javascript will change the style of the page without CSS
            document.body.style.color = "green";
            document.body.style.backgroundColor = "blue";
            document.body.style.textAlign = "center";
        </script>
        <p>lol</p>
    </body>
</html>


There are some subtle differences in this snippet;
  1. The script is placed in the body tag. The reason this is placed in the body tag is because it refers to the body on the fly, and I cant place it in the header because while the page is loading, the script will run when there is no body.
  2. There is no CSS. As you can see, there is absolutely no CSS here.
  3. The DOM is used to change the page. The syntax goes all the way from the document to the body itself, to its style attributes and finally to its different attributes such as background color and aligning.
  4. The document represents the actual page.
  5. The body represents the <body> tag.
  6. The style represents the style of the previous object. In this case, the <body> tag.
If your familiar with CSS you may notice something slightly different. All the attributes are named the same, except slightly different. In CSS, attributes such as font-weight or background-color use dashes to seperate words, while the DOM uses capitalization such as fontWeight and backgroundColor instead.


Of course, you can also accomplish this task with events. In this next example, im going to show you how to use button events to edit the DOM using javascript functions.
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Manipulating the DOM through Button Events</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
 
        function changeColors(color, bgcolor) {
            document.body.style.color = color;
            document.body.style.backgroundColor = bgcolor;
        }
 
    </script>
  </head>
  <body>
      <h1>Edit the DOM through button events and Javascript</h1>
      <fieldset>
          <input type="button" onclick="changeColors('black', 'white')"
                 value="Black and White" />
          <input type="button" onclick="changeColors('green', 'blue')"
                 value="Green and Blue" />
      </fieldset>
  </body>
</html>
 
  1. A button event calls a function which edits the DOM. A javascript function edits the DOM. A button is used to call this function.
  2. Embedding quotes within quotes. Take a look at the onclick lines, you will notice the function parameters are enclosed in single quotes ('). This is the case because if double quotes where used as usual, the browser would nest the quotes as "changeColors(" and white")".
  3. Script is placed in the head. Now that the script isnt used immediately when the page loads, the script is instead placed in the <head> tag.
Thats some basic DOM manipulation. The DOM isnt just limited to editting the styles of pages, it can do many other things.

Next, we are going to manipulate forms and different types of input using the getElementById() function from the document object. In order to use this function, you must specify an id for the element you want to modify. Here is a simple script which takes a specified name from one input field, and prints out a sentance in another.
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Manipulating the DOM through Button Events</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
 
        function submit() {
            var name = document.getElementById("name").value;
            var output = document.getElementById("output");
            output.value = "Hello " + name + "!";
        }
 
    </script>
  </head>
  <body>
      <label for="name">Name: </label>
      <input type="text" id="name" />
      <br />
      <input type="button" id="name" value="Submit"
             style="width:10%" onclick="submit()" />
      <br />
      <label for="output">Output: </label>
      <input type="text" id="output" />
  </body>
 

</html>
  1. The submit button outputs the data. The submit() function uses two variables: name and output. The getElementById() function references the textfield with the specified id and the value property holds the data inside the textfield.
  2. Both textfields have an id. Both textfields hold an id, in order to use the getElementById() function, there must always be an id assosciated with the element the function will reference.
Thats useful and all, but what if we want to actually edit a page? A textbox isnt the best way to output data. So instead, I introduce to you the innerHTML property. This property describes the HTML data in an element. Take a look at this example;
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Using innerHTML</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
 
        function submit() {
            var name = document.getElementById("name").value;
            var output = document.getElementById("output");
            output.innerHTML = "<em>" + name + "</em>";
            output.innerHTML += ", welcome to the site!";
        }
 
    </script>
  </head>
  <body>
      <fieldset>
        <label for="name">Name: </label>
        <input type="text" id="name" />
        <br />
        <input type="button" id="name" value="Submit"
            style="width:10%" onclick="submit()" />
      </fieldset>
      <br />
      <div id="output">
      </div>
  </body>
 

</html>
  1. Validators get confused by forward slashes. When you want to use a / in javascript strings, you must proceede it with a backslash.
When dealing with input elements such as a list box, you need to create a variable and use the getElementById() function as usual then loop through the lists contents. Use the selected property (boolean) to determine whether or not a list item is selected. The checked property will determine whether or not a checkbox is checked.

Radio buttons are quite different. They require a new attribute and manipulating the DOM is slightly different. In order to interpret radio buttons, you would use the getElementsByName() function and the name attribute.
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Manipulating the DOM through Button Events</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
 
        function submit() {
            var part1 = document.getElementsByName("part1");
            var part2 = document.getElementsByName("part2");
 
            for (i = 0; i < part1.length; i++) {
                var name = part1;
                if (name.checked)
                    var selectedName = name.value;
            }
 
            for (i = 0; i < part2.length; i++) {
                var name = part2;
                if (name.checked)
                    var selectedName2 = name.value;
            }
            var output = document.getElementById("output");
            var outputText = selectedName + selectedName2;
            output.innerHTML = outputText;
        }
 
    </script>
  </head>
  <body>
      <h1>Match the proper names...</h1>
      <fieldset>
        <input type="radio" name="part1" id="rune" value="Rune" />
        <label for="rune">Rune</label>
 
        <input type="radio" name="part1" id="tune" value="Tune" />
        <label for="tune">Tune</label>
 
        <input type="radio" name="part1" id="dune" value="Dune" />
        <label for="dune">Dune</label>
 
        <br /><br />
 
        <input type="radio" name="part2" id="mocus" value="Mocus" />
        <label for="mocus">Mocus</label>
 
        <input type="radio" name="part2" id="focus" value="Focus" />
        <label for="tune">Focus</label>
 
        <input type="radio" name="part2" id="locus" value="Locus" />
        <label for="dune">Locus</label>
      </fieldset>
        <br />
        <input type="button" id="name" value="Submit"
            style="width:10%" onclick="submit()" />
      <br />
      <br />
      <div id="output">
 
      </div>
  </body>
</html>
 
  1. The getElementsByName() function returns an array of all radio buttons in a group. This function returned an array of 3 values (the size of all the options).
  2. All choices are iterated. All radio buttons are iterated through, and the if statement checks whether the button is selcted. If so, a new variable is made to hold the value of that button.
  3. Finally, the output div holds the two values. Both values from the two radio buttons are concatenated and are printed out using the innerHTML property.
  4. The name attribute is used for each radio button. This is used to distinguish between the two different radio button groups.
Thanks for reading my tutorial on basic manipulation on the DOM with Javascript, if you have any questions please message me here.
  
adsense code2.3
Closed Thread

Bookmarks

Javascript and the DOM

Programming




Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
adsense2.6
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -7. The time now is 06:33 PM.





Powered by vBulletin® Version 3.8.8
Copyright ©2000 - 2017, vBulletin Solutions, Inc.