I'm new to javascript and I'm not using jQuery.
I'm trying to make my function btnHandle() run when I click the button.
However, I found that
btn.onclick = btnHandle();
is different from
<button id="sort-btn" onclick="btnHandle()">submit</button>
When I use btn.onclick = btnHandle();, the btnHandle() function is executed when I refresh the code without clicking the button.
I want the function be executed only when the button clicked.
<button id="sort-btn" onclick="btnHandle()">submit</button> works as I want.
Why the previous one not working well? Why the onclick event is fired the the page is loaded?
<button id="sort-btn" onclick="btnHandle()">submit</button>
<script type="text/javascript">
function btnHandle() {
var aqiData = getData();
aqiData = sortAqiData(aqiData);
render(aqiData);
}
function init() {
var btn = document.getElementById("sort-btn");
// btn.onclick = btnHandle();
}
init();
</script>