Reputation: 15
I am newbie so this question may be sound stupid. I want to load a javascript function using <body onload="function()">
but i want to handle this event through on/off switch so if the switch is on(by default) the "onload" event will call the function and if the switch is set to off it will not.
Thanks in advance!
Upvotes: 0
Views: 698
Reputation: 17
<h1 id="changetext"> status is here</h1>
<button id="alertme" onclick="bulb();" >ON</button>
<script>
var flag = 0;
function bulb(){
if (flag==0) {
window.alert(flag);
document.getElementById('alertme').innerHTML = "OFF";
document.getElementById('changetext').innerHTML = "Machine is off";
flag=1;
}
else {
window.alert(flag);
document.getElementById('alertme').innerHTML = "ON";
document.getElementById('changetext').innerHTML = "Machine is on";
flag=0;
}
}
</script>
Upvotes: 0
Reputation: 1757
If you want to execute a function when the document is loaded, you should use the window onload event, or alternatively, and maybe more accepted solution is to use jquery (look into it, better learn the best practice from the beginning)
$(function(){
// my_on_load_script;
});
If you'd like to create a toggle button in javascript, you may use jquery (again), to toggle styles applied to the button element something along the lines:
$('#my_button_identifier').click(function(e){
$(this).toggleClass('my_toggled_button_class');
);
here you go: http://api.jquery.com/toggleClass/
Upvotes: 1