Reputation: 411
I am newbie to Javascript, I have difficulties getting the meaning of this code properly. I would like to share my thought over the code,and I need your guidance to understand it correctly.
<body>
<form>
<input type="button" value="Click Me!" id="say_hi" />
</form>
<script type="text/javascript" src="js_event_01.js"></script>
</body>
function hi_and_bye() {
window.alert('Hi!');
window.alert('Bye!');
}
var hi_button = document.getElementById("say_hi");
hi_button.onclick = hi_and_bye;
My understanding: the event "onclick" calls the function "hi_and_bye" when ID is "get_alerts". Similarly this could be applied to any event, and I can give an id attribute to any element and that id would be responsible to make an accessible corresponding input element.
Upvotes: -1
Views: 139
Reputation: 1039428
Your understanding is correct. You could give an id
to any DOM element, not only inputs. Then using the getElementById
you could retrieve a reference to this element.
In this example that's what you are doing:
// Get a reference to a DOM element that has id="say_hi"
var hi_button = document.getElementById("say_hi");
// subscribe to the onclick event handler of the DOM element we retrieved on
// the previous line and attach this handler to the hi_and_bye javascript function
hi_button.onclick = hi_and_bye;
I don't think that the body of the function itself requires any more explanation: it will just display 2 alerts once after the other when this function executes.
Upvotes: 1