X

Get in Tutch

Begginners HTML Guide

Introducing Javascript

Previously we learnt some advanced CSS. This blog is the final week of our tutorials and we will be covering the basics of Javascript. Javascript is the most widely used programming language available, It is used on the Web, for computers, servers, laptops, tablets, smart phones, and more.

The smart thing about Javascript is that you can manipulate HTML elements.

Lets start by Creating a new HTML file with the following content, we are not using any CSS here, also download these images and put them in the same directory as the HTML file (right click and ‘save image as’ to download the images)

bulboff bulbon

<html>
<body>

<img id=”lightbulb” src=”bulb_off.gif” width=”100″ height=”180″>

<p>Click the light bulb to turn on/off the light</p>

</body>
</html>

Notice we have added an ID to our image, this is so we can use javascript to communicate with it. Now we will add an On Click action to the image, the action will be a function we will soon create.

<html>
<body>

<img id=”lightbulb” onclick=”changeImage()” src=”bulb_off.gif” width=”100″ height=”180″>

<p>Click the light bulb to turn on/off the light</p>

</body>
</html>

Now we can write our script to change the image when we click it.

<script>
function changeImage() {
var image = document.getElementById(‘lightbulb’);
if (image.src.match(“bulbon”)) {
image.src = “bulboff.gif”;
} else {
image.src = “bulbon.gif”;
}
}
</script>

Put this in the top of your HTML file like so.

<html>
<body>
<script>
function changeImage() {
var image = document.getElementById(‘lightbulb’);
if (image.src.match(“bulbon”)) {
image.src = “bulboff.gif”;
} else {
image.src = “bulbon.gif”;
}
}
</script>

<img id=”myImage” onclick=”changeImage()” src=”bulboff.gif” width=”100″ height=”180″>

<p>Click the light bulb to turn on/off the light</p>

</body>
</html>

Now when we click the lightbulb it will “turn on and off”.

We hope we have taught you some things you maybe didnt know before we started our Beginners HTML series. All good things must come to an end, We will be sharing some knowledge on PhP in the upcoming weeks. Stay tuned.