A Pen by Chris Barr

Thumbnail
This awesome code was written by chrismbarr, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright chrismbarr ©

Technologies

  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>A Pen by  Chris Barr</title>
  
  
  
  
  
</head>

<body>

  <input type="number" min="1" max="12" value="12" />
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/chrismbarr/a-pen-by-chris-barr-zrOgYW */
var inputTimer = null;

function cycle(element) {
  if (element.attributes.max && element.attributes.min) {
    var prevVal = element.value;
    inputTimer = setTimeout(function() {
      if (prevVal === element.attributes.max.value) {
        element.value = element.attributes.min.value;
      } else if (prevVal === element.attributes.min.value) {
        element.value = element.attributes.max.value;
      }
    }, 50);
  }
}

$("input[type='number']")
  .on("mousedown", function(e) {
    //this event happens before the `input` event!
    cycle(this);
  }).on('keydown', function(e) {
    //up & down arrow keys
    //this event happens before the `input` event!
    if (e.keyCode === 38 || e.keyCode === 40) {
      cycle(this);
    }
  }).on('input', function(e) {
    //this event happens whenever the value changes
    clearTimeout(inputTimer);
  });

Comments