ARTLUNG LAB Share

Created September 13, 2010. Modernized November 30, 2024.

Goal of 50!

Uses localStorage to keep track of a goal. Inspired by this question in Ask Metafilter: Counting Up to a set number with an Image??

0

HTML

    <div class="goal50">
        <div id="counter">
            0
        </div>
        <footer>
            <button id="increment">+1</button>
            <button id="decrement">-1</button>
        </footer>
    </div>

SCSS

.goal50 {
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  width: clamp(200px, 100%, 600px);

  > * {
    width: 100%;
  }

  #counter {
    font-weight: bold;
    text-align: center;
    font-size: 4rem;
    color: #666;
    text-shadow: 0.2rem 0.2rem #eee;
    height: 500px;
    background: linear-gradient(to top,
            green calc(2% * var(--count, 0)),
            #ccc 0
    );
    display: flex;
    justify-content: center;
    align-items: center;


  }

  footer {
    display: flex;
    justify-content: center;
    align-items: center;

    button {
      font-size: large;
      padding: 1rem;
      width: 100%;
    }

  }
}

JavaScript

var GOAL = {
    DEFAULT_COUNT: 0
    , GOAL_COUNT: 50
    , key: 'goalCount'
    , init: function () {
        if (window.localStorage.getItem(this.key) === null) {
            this.setCount(this.DEFAULT_COUNT);
        }
        this.updateDisplay();
        return this;
    }
    , getCount: function () {
        return parseInt(window.localStorage.getItem(this.key), 10);
    }
    , setCount: function (val) {
        if (val < 0) {
            val = 0;
        }
        if (val > this.GOAL_COUNT) {
            val = this.GOAL_COUNT;
        }
        window.localStorage.setItem(this.key, val);
        this.updateDisplay();
        return this;
    }
    , incrementCount: function () {
        this.setCount(this.getCount() + 1);
    }
    , decrementCount: function () {
        this.setCount(this.getCount() - 1);
    }
    , updateDisplay: function () {
        let counterElem = document.querySelector('#counter');
        counterElem.textContent = this.getCount();
        counterElem.setAttribute('style', '--count: ' + this.getCount() + ';');
    }
};
document.addEventListener('DOMContentLoaded', function () {
    GOAL.init();
    document.getElementById('increment').addEventListener('click', function () {
            GOAL.incrementCount();
        }
    );
    document.getElementById('decrement').addEventListener('click', function () {
            GOAL.decrementCount();
        }
    );
});