Calling a function using an HTML button
I wonder what I am doing wrong in this case? I got this button which is an HTML element. When I click on it, I want the push () function to be activated. Unfortunately my console says:
ReferenceError: push is undefined
Can anyone help me in this case? Many thanks!
<button type="button" onclick=push()>Click Me!</button>
<script type="text/javascript">
function push (){.....};
</script>
+3
source to share
2 answers
You can do this instead:
You can do this if you want to use the push () function with only one button,
<button type="button" id="clickme">Click Me!</button>
<script type="text/javascript">
document.getElementById("clickme").addEventListener("click", function() {.....}
</script>
And if you want to use push () function with multiple buttons,
<button type="button" id="clickme">Click Me!</button>
<script type="text/javascript">
document.getElementsByClassName("clickme").addEventListener("click", function() {.....}
</script>
Pros: Less HTML Cons: More javascript
-1
source to share