I'd suggest you to use addEvent
,removeEvent
function approaches due to cross browser issues.
addEvent
function is capable of to add events on elements, while removeEvent
remove them
if [ document.addEventListener ] { // if addEventListener provided
this.addEvent = function[elem, type, fn] {
elem.addEventListener[type, fn, false];
return fn;
};
this.removeEvent = function[elem, type, fn] {
elem.removeEventListener[type, fn, false];
};
} else if [ document.attachEvent ] { // if attachEvent provided
this.addEvent = function[elem, type, fn] {
var bound = function[] {
return fn.apply[elem, arguments];
};
elem.attachEvent["on" + type, bound];
return bound;
};
this.removeEvent = function [elem, type, fn] {
elem.detachEvent["on" + type, fn];
};
}
For example if you have HTML
JavaScript
addEvent[document.getElementById["source"],"keydown",function[]{ // event will occur on keyup
document.getElementById["result"].innerHTML = this.value; // this refers to textarea element
}];
JSFiddle
PS. Check out attachEvent and addEventListener methods
My function is a timer that should run when the page is displayed. I wrote
startcountdown[];
In html but this doesn't work. How can I call that function? I don't need special event to happen before calling it.
asked May 3, 2016 at 11:05
Sargsyan GrigorSargsyan Grigor
4911 gold badge4 silver badges19 bronze badges
10
window.onload = function[] {
startcountdown[];
}
answered May 3, 2016 at 11:11
overburnoverburn
1,1349 silver badges26 bronze badges
You may use JavaScripts native window.onload
function, if you are not using any other library like jQuery or something else.
window.onload = function[] {
startcountdown[];
};
I'd also like to mention that you could also start a function by just adding it to the end of your markup. That being said, if you define a function function startcountdown[] { }
at the very beginning of your html, you could simply use startcountdown[];
at the very end of your html [e.g. before your closing tag].
This approach would simply execute your function after your DOM has being loaded, since it's defined as the last call of your markup.
answered May 3, 2016 at 11:11
Aer0Aer0
3,63416 silver badges32 bronze badges
you can put it into tag using 'onload' event:
or just use jQuery:
$[document].ready[function[] {
yourFunct[];
}];
answered May 3, 2016 at 11:19
Pardeep PathaniaPardeep Pathania
1,3402 gold badges15 silver badges22 bronze badges
you can try this put onload="startcountdown[];"
in html body tag
answered May 3, 2016 at 11:28
By calling your function in page on-load
window.onload = startcountdown;
function startcountdown[]{
//write your code here
}
answered May 3, 2016 at 11:20
nisarnisar
1,0451 gold badge11 silver badges26 bronze badges