Last active
August 29, 2015 14:18
-
-
Save rodrigopedra/dd9aae735e743daf4ddb to your computer and use it in GitHub Desktop.
jQuery Counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>jQuery Counter</title> | |
</head> | |
<body> | |
<!-- declarative markup --> | |
<div class="my-counter"> | |
<h1>Counter: <span class="counter-output"></span></h1> | |
<button type="button" data-increment="-1">subtract 1</button> | |
<button type="button" data-increment="1">add 1</button> | |
</div> | |
<!-- with custom markup --> | |
<p class="my-counter"> | |
<strong class="counter-output"></strong> counted! | |
<a href="#" data-increment="-10">subtract 10</a> | |
<a href="#" data-increment="5">add 5</a> | |
</p> | |
<script src="http://code.jquery.com/jquery.min.js"></script> | |
<script src="js/components/counter.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
'use strict'; | |
$('.my-counter').each(function ( index, element ) { | |
var count = 0; | |
var $component = $(element); | |
var $output = $component.find('.counter-output'); | |
var updateCount = function( increment ) { | |
count += increment; | |
count = count < 0 ? 0 : count; | |
$output.text(count); | |
}; | |
$component.on('click', '[data-increment]', function ( event ) { | |
var increment = $(event.target).data('increment'); | |
updateCount(+increment); | |
}); | |
updateCount( count ); //initial state | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment