Brenelz Web Design Solutions

Web programming, the brenelz way!

Brenelz's Web Development Tips


Client-Side Javascript

Today I have decided to give you some insight into client-side programming instead of server-side. Frankly, I do the majority of my work on the server using technologies such as PHP, ASP.NET, Perl, and so on. These technologies have their purposes, but nothing beats the interactivity that JavaScript provides.

When I started in web design, I have to admit I was completely lost in programming JavaScript and I felt that there wasn’t any need to learn it at the time. I felt more comfortable with the PHP syntax than JavaScript. The only time I would use JavaScript would be premade scripts from DynamicDrive.com.

I then went to University and learnt the fundamentals of CSS, JavaScript, and the technique of eliminating page refreshes called AJAX. I got a little glimpse of the power that JavaScript has. One thing to always keep in mind is only use JavaScript if you think it will enhance the user’s experience, and make sure you take into consideration that JavaScript can easily be disabled.

JavaScript can create elements on the fly and insert them into the DOM (Document Object Model).

// create an empty div element
var element = document.createElement("div");

// change the background-color css style
element.style.backgroundColor = "black";

// create an action when the event onmouseover is activated
element.onmouseover = function() {
alert("boo!");
};
var text = document.createTextNode("my text inside the div");

// add text as a child of our element
element.appendChild(text);

In HTML this has been created:

<div>
my text inside div
</div>

We can now append this to a <body id=”home”> tag

// access the element we want
var body = document.getElementById("home");
body.appendChild(element);

With this simple example we have dynamically created a div through JavaScript. We can now put this in a function that will be called via the onclick event, and a div will be created when we click the link. Pretty neat eh?

I will now leave you with some homework, in order that you research and experiment with the following functions/properties:

XMLHttpRequest() – Basis of AJAX
setAttribute() – sets an elements attribute dynamically
removeChild() – remove an elements child
document.getElementsByTagName(”a”) – gets all anchors on the page


Post a Comment

Your email is never shared. Required fields are marked *

*
*

Copyright © 2008 Brenelz Web Solutions.

Winnipeg Web Development by Brenelz Web Design Solutions Logo Brenelz Web Solutions