Pages

JavaScript call and apply

JavaScript call and apply are functions that are used to call function within the context of another function. There is a fundamental difference between the two, call() takes parameters as a name while as apply() accepts parameters as an array.

I will show how to use call and apply to change the background of a page in JavaScript. Usually you won’t do such a basic thing as changing background via call or apply methods, but I wont to touch the basics of apply and call and show how to use them in function context. Otherwise you would never want to change the page background or for that matter any style property with JavaScript call and apply methods.

JavaScript call() function with Example.
   
function changeBackgroundColor(color) 
{
            this.style.backgroundColor = color;
            this.innerHTML = "<h1>Body Background Changed Via JavaScript Call Function</h1>";
 }
 var bodyBackground = document.getElementsByTagName("body")[0];
 changeBackgroundColor.call(bodyBackground,"#990000");


Quite simple, we use a function changeBackgroundColor(), pass it a parameter color. In this function we set the bodybackground with the follow statement
this.style.backgroundColor = color;
we also set the innerHTML of body to be a h1 tag with some descriptive text.

Now to call changeBackgroundColor function we use call like changeBackgroundColor.call(bodyBackground,”#990000″);

As I said call takes parameters as name, the bodyBackground is the node that we want the background to be changed. In our case body tag, the we pass the color that page background should take.

See the Demo of the above example in jsFiddle:

No comments:

Post a Comment