user2903379
user2903379

Reputation: 385

Javascript counter increment not working

I have a counter on my html page and im trying to use a button to increment the counter by 1 when using the + button, and decrease the counter by 1 when using the - button, with a maximum of 10 counts (0 minimum). Problem is the javascript doesnt seem to work at all. When I click the buttons, nothing happens. I have google hosting jquery in my header. I've tried this on js fiddle and it works but not on my page. Any help would be greatly appreciated.

html (these are inside a div)

   <button onclick="countDown();">-</button>
            <span id="counter">0</span>
            <button onclick="countUp();">+</button>

Javacript

    <script type="text/javascript">
    var minVal = 0, maxVal = 10, clicks = 0,
 display = document.getElementById("counter");

    function countUp() {
        clicks = Math.min(maxVal, clicks + 1);
        display.innerHTML = clicks;
    }

    function countDown() {
        clicks = Math.max(minVal, clicks - 1);
        display.innerHTML = clicks;
       }
</script>

Edit: the script is in my header after the jquery script

Upvotes: 0

Views: 1218

Answers (1)

Jonathan Lam
Jonathan Lam

Reputation: 17351

The problem most likely is that display is not set, because the document has not loaded yet, and therefore document.getElementById("counter") would not return an element (the #counter element does not exist yet). Instead of putting the script in the header, try putting it after the #counter span.

You can check to see if this is true by opening the console. If there is an error message, something along the lines of Error: trying to set property "innerHTML" of undefined, that would be the problem.

Here is a working JSFiddle.


And this isn't just a question-specific tip— you almost always want to have your JavaScript load after the DOM (the HTML) loads. So either enclose all your script in a window.onload or $(document).ready() (jQuery) event handler, or put the script at the end of the <body> as was this case.


Per your request in the comments, if you want to use an external script, do the same thing. Put it an external file and include it with a <script src="yourscript.js"></script> at the end of the body, and it should do just the same.

Upvotes: 1

Related Questions