Reputation: 3819
This is the code which I have written. The default
function should be called when the page loads, without clicking any button. It should display some data and then two buttons should be displayed. What modifications do I need in that code?
I am a beginner so I may have missed many things please help.
This is my JavaScript part, detailed program is given in the link.
function default(){
var i=7;
j=15;
document.write(i+j);
}
Upvotes: 1
Views: 773
Reputation: 150313
You can use Immediately Invoked Function Expression
:
(function defaults() { // I edited the function name - "default" can not be used
var i = 7; // You can also remove the function name, will work either
j = 15; // way. "default" is a reserved word
document.write(i + j);
})();
But it's calling it... you can't run a function without calling it, do you want to execute it with magic?
You should read this:
What does this "(function(){});", a function inside brackets, mean in javascript?
As @stakx pointed out, you can pass a function reference to functions the execute the function after X time, like setTimeout
:
setTimeout(defaults, 1000); // execute "defaults" after one second.
But it's just like handle it yourself:
function foo(aFunction){
aFunction();
}
foo(defaults);
Upvotes: 4
Reputation: 84835
If you're not going to use jQuery (as suggested by @Photon Critical Fatal Error), you could give the body
element's onload
event a try:
<body onload="default();">
...
</body>
Though this might not work as expected. jQuery handles this in a more reliable way, so if you decide to give it a try, look at the $(document).ready(…)
API function.
Upvotes: 2
Reputation: 268482
You cannot use the keyword default
:
Uncaught SyntaxError: Unexpected token default
You'll need to rename your function.
Once you've done that, you can wrap it in parenthesis to execute it immediately:
(function dflt(){
var i = 7, j = 15;
document.write( i + j );
})();
document.write
Note that document.write
will clear out your document, thus removing the contents of your document. You should instead insert a new text node, or update the contents of an element on the page:
(function dflt(){
var i = 7, j = 15;
document.body.appendChild( document.createTextNode( i + j ) );
})();
You could also add this text node to an element on the page:
var tNode = document.createTextNode( i + j );
document.getElementById("foo").appendChild( tNode );
This would add the resulting text to any element whose id
attribute is foo
:
<span id="foo"></span>
Upvotes: 7
Reputation: 20155
function default(){
var i=7;
j=15;
document.write(i+j);
}
default is a reserved word in javascript you cant use it.
Upvotes: 1