3

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;
}
2
  • Please include the most relevant portions of code within your post. Links are often welcome for providing additional context, but shouldn't be the only reference. Commented Mar 29, 2016 at 5:56
  • You could wrap it in an IIFE, then add event listeners to the relevant divs instead of having the onclick property. Commented Mar 29, 2016 at 6:02

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.