Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Aug 2002
    San Francisco
    Thanked 15 Times in 15 Posts

    incrementing and decrementing not behaving as expected

    I have a counter set to 1 and five individual buttons. When I click on a button I want it to add 1 to or subtract 1 from the counter. I'm using the counter to keep track of how many divs are displayed on screen so that I can set their widths.

    What I expected to happen is that when I click a button the first time it increments. The second time it decrements. If I click all 5 buttons 1 time I expected the counter to equal 5. But instead the counter equals 2. What do I need to change in my code to get the expected results?

    var counter = 1;
    function setCounter() {
    	$(this).toggle(increment, decrement);
    function increment() {
    function decrement() {
    <a href="javascript:setCounter()">Avg Salary Leaderboard</a><br />
    <a href="javascript:setCounter()">Min Salary Leaderboard</a><br />
    <a href="javascript:setCounter()">Max Salary Leaderboard</a><br />
    <a href="javascript:setCounter()">BA+30 Step 1</a><br />
    <a href="javascript:setCounter()">BA+60 Step 10</a><br />
    Outside of a dog, a book is man's best friend. Inside of a dog it's too dark to read. Groucho Marx

  2. #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Sydney, Australia
    Thanked 932 Times in 919 Posts
    You shouldn.t be attaching the JavaScript to the links like that. If you attach them properly then you will be a step closer to getting it to work.

    Links coded that way are supposed to be right clicked on to save the script as a bookmarklet. The JavaScript doesn't keep track of which one is clicked on as each is running in global scope and not the scope of the link.

    To get you started. Recode the links as follows

    button { border:0; background-color:inherit; color:#00f; text-decoration:underline; cursor:pointer;}
    <div id="links">
    <button>Avg Salary Leaderboard</button><br />
    <button>Min Salary Leaderboard</button><br />
    <button>Max Salary Leaderboard</button><br />
    <button>BA+30 Step 1</button><br />
    <button>BA+60 Step 10</button><br />
    Then from within the JavaScript attach a click event listener to the div tag.
    Last edited by felgall; 01-31-2014 at 11:13 PM.
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts