Reputation: 101
I have a simple example of Javascript event bubbling on this jsfiddle (click on the man and it will bubble up to pig). How would I use a closure to get var interval = 0;
out of the global scope, but retain the onclick="display('sometext')"
in the html?
var interval = 0;
function display(animal) {
window.setTimeout(function() { showText(animal) }, interval);
interval = interval+300;
window.setTimeout(function() { clear() }, interval);
}
function showText(animal) {
$(".alGore").text(animal.toUpperCase());
$("."+animal+"-box").css({'background-color':'#ff0'});
}
function clear(animal) {
$(".alGore").text('');
$("*").css({background: 'transparent'});
interval = 0;
}
Upvotes: 3
Views: 2079
Reputation: 1577
You can just wrap function in another function to make a closure. But since you have two functions which you want to bind to the same closure you need an object.
Check this out https://jsfiddle.net/axrpcaq4/16/:
var animalBox = function(){
var interval = 0;
return {
display: function(animal) {
var that = this;
window.setTimeout(function() { that.showText(animal) }, interval);
interval = interval+300;
window.setTimeout(function() { that.clear() }, interval);
},
showText: function(animal) {
$(".alGore").text(animal.toUpperCase());
$("."+animal+"-box").css({'background-color':'#ff0'});
},
clear: function(animal) {
$(".alGore").text('');
$("*").css({background: 'transparent'});
interval = 0;
}
}
}();
And HTML:
<div class="center">
<div class="pig-box center" onclick="animalBox.display('pig')">
<img src="http://i.imgur.com/MumugGd.png" alt="pig" class="icon">
<div class="bear-box center" onclick="animalBox.display('bear')">
<img src="http://i.imgur.com/p7L5DHL.png" alt="bear" class="icon">
<div class="man-box center" onclick="animalBox.display('man')">
<img src="http://i.imgur.com/cKvJT7T.png" alt="man" class="icon">
</div>
</div>
</div>
<div class="alGore"></div>
</div>
Upvotes: 3