0

There's a great little bit of falling confetti generating JavaScript that I found on CodePen. It's invoked by a simple:

(function() {
    // Confetti code here
}).call(this);

It works great, but I wish to manually invoke it at a certain point.

I've tried placing it in a function, like so (removing the two wrapping lines above):

function confetti() {
   // Confetti code here
}

And then calling that function, but nothing is happening. Can't see why. The code in question can be seen here: http://codepen.io/linrock/pen/Amdhr

UPDATE

It appears my code was triggered fine. It had nothing to do with it being an anonymous function at all. For some reason it only springs to life when the browser is resized -- which is another issue entirely. Weird.

Not sure what to with this question now -- the solutions here have nothing to do with the actual problem. (The problem as described never existed in the first place :-/ )

Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
  • [Function.prototype.call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) - although I don't think that's actually your problem. – Matt Burland Oct 29 '15 at 17:47
  • Have a look at [Reason behind this self invoking anonymous function variant](http://stackoverflow.com/q/6287511/1048572) – Bergi Oct 29 '15 at 17:50

2 Answers2

3

You're close, the attempt you've shown is just not invoking it;

function confetti() {
   // pass
}
confetti.call(this);

However as you want to use it elsewhere, I won't assume this will be the same, so instead I would write

var confetti = (function () {
    // pass
}).bind(this);

confetti();

You can read the docs on call here and bind here

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • Rats. The function is being called, but the confetti still isn't falling? http://jsfiddle.net/JohnnyWalkerDesign/pmfgexfL/ – Chuck Le Butt Oct 29 '15 at 18:02
  • Turns out my original code works exactly the same as this code. The problem is with the canvas, not the way the anonymous function was called. – Chuck Le Butt Oct 29 '15 at 18:25
1

The function that allows you to trigger the animation is called step. You just need to remove it's call from the code. So instead of having:

window.step = function() {
    var c, j, len, results;
    requestAnimationFrame(step);
    context.clearRect(0, 0, w, h);
    results = [];
    for (j = 0, len = confetti.length; j < len; j++) {
      c = confetti[j];
      results.push(c.draw());
    }
    return results;
  };

  step();

You have

window.step = function() {
    var c, j, len, results;
    requestAnimationFrame(step);
    context.clearRect(0, 0, w, h);
    results = [];
    for (j = 0, len = confetti.length; j < len; j++) {
      c = confetti[j];
      results.push(c.draw());
    }
    return results;
  };

And now you just need something that will trigger it manually:

step();
LUIS PEREIRA
  • 478
  • 4
  • 20