Javascript Basics : Part 2 (Functions)


Suppose I want to change the button color when it is clicked. And to do this task, I don’t want to send the page to the server. So, what should I do?
Well, HTML DOM has given us some events to work with. We will use one the events, Click event and put some code on its event.
The below code will change the button color if clicked on that.


Now, if we want to add another button and apply same functionality with the click, the code will like below


But if you look closely, we are repeating the code. This is the worst smell of the code smells. So, we should create a method and call that method from the click event.

So, how do we create a function in Javascript? Its easy. As we did before, we must add the ‘script’ tag first. Inside of this tag, we will write the function. In javascript, we must write the word ‘function’ before the name of the function. For example:
function MyFunctionName() {
}

Then we will call that function from the event. So, if we refactor the above html code, we will get the below

    function ChangeColor() {
        document.bgColor = "#ffaaff";
    }

Total Code:



Please note that, we can write the functions anywhere in the page inside of html tag. But it is good practice to put the function inside of the head tag.
We can pass parameter in javascript functions. In our above example, we can pass the color code from the button tag to the function. The calling part should be like this:

onclick="ChangeColor('#ffaaff')"

The function definition will be:

    function ChangeColor(color) {
        document.bgColor = color;
    }

Total code:



We can also return from a javascript function. But unlike C# and other common languages, Javascript function don’t have any return type with its definition. We will just return the result at the end of the method.
Now, according to our above scenario, we can get our required color using another function instead of passing the color code from the button tag.

So, we will have two functions. One will check and return the color code and the other function will be called from the button tag.

function GetColor() {
        if (document.bgColor.toString() == "#ffaaff") {
            return "#ffffff";
        }
else if (document.bgColor.toString() == "#ffffff") {
            return "#ffaaff";
        }
        return "#ffffff";
    }

    function ChangeColor() {
        document.bgColor = GetColor();
    } 

Total code:


Quick Test 
 If we want to display square of a number, we will add script the calling part in the 'body' tag and return the square from a Javascript function. I hope you can do it. If you can't just let me know. 

I will try to post about the events in my next blog post. 

Comments

Popular posts from this blog

Dropbox as SVN Repository

While Loop and Variable Casting in SQL Script