0

I am new to javascript and am trying to code a click event handler for an html button element with id="display". When I use a window.onload function and add my .onclick event it runs when the window loads and doesn't wait for the click event. I have tried .addEventListener('click', dispResults) method and although the dispResults function doesn't run onload, it doesn't run with the click event either. Please help...

var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];

var $ = function (id) {
    return document.getElementById(id);
}

var dispResults = function () {
    var avg;
    var total = 0;
    for (var i = 0; i < scores.length; i++) {
        total = total + scores[i];
    }
    avg = total/scores.length;
    $("results").value = avg.toFixed(0);
}

window.onload = function () {
    $("display").onclick = dispResults();
}

Thank you.

  • Short answer: remove the `()` from `= displayResults()`, because that is what calls the function. It is possible the problem you mention with `.addEventListener('click', dispResults)` is *not* a duplicate, because that should work given you put `dispResults` without the `()`, but you don't actually show that in context - if you want help with that please [edit] your question to cover that specifically and we could reopen it. – nnnnnn Jul 08 '16 at 01:45
  • P.S. Why the jQuery flag? It is confusing when you have defined your own `$()` function as a shortcut to `getElementById()`, and don't use any jQuery in your code. – nnnnnn Jul 08 '16 at 01:49
  • I added the jquery flag as the class I am taking is javascript and jquery. I don't really understand yet where the line is between the two. It works great without the parentheses as you point out. What are the parentheses really doing when left in place? – Chris Wolter Jul 08 '16 at 03:43
  • Did you read the answers at the linked duplicate? The parentheses call the function. If you say `$("display").onclick = dispResults()` that immediately calls the `dispResults` function and then assigns its return value (which is `undefined`) to the onclick. If you say `$("display").onclick = dispResults` then that assigns a reference to the function to the onlcick. – nnnnnn Jul 08 '16 at 03:48
  • Regarding JavaScript versus jQuery: JavaScript is a language. jQuery is not a language, it is "just" some JavaScript code that somebody else wrote to create a collection of useful functions so that you don't have to bother writing them yourself. That is, jQuery is a library of useful JavaScript functions, most of which are for manipulating HTML elements. – nnnnnn Jul 08 '16 at 04:00

0 Answers0