Talking about Javascript.
Today I needed to create some kind of draft explosion using only jQuery, I browsed the web but I did not find anything quick, light and simple so I decided to create a plugin on my own, since it’s a matter of minutes.
All I need to do is to create a particle blast, which is basically a set of <div>.
I am going to share the code with you, although uncommented, because it’s very easy to understand either to manage particles in jQuery and to see how to create your own jQuery plugins:
<html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script> <script type="text/javascript"> // THE MAIN SCRIPT, TO GENERATE AN EXPLOSION ON MOUSE CLICK $(document).ready(function() { $(document).click(function(e) { var xClick = e.clientX; var yClick = e.clientY; $("body").explosion({ origin:{ x:xClick, y:yClick }, particleClass:"particle" }); }); }); // EXPLOSION PLUGIN (function($){ $.fn.explosion = function(options){ var settings = $.extend({ particleClass: "particle", origin: {x:0,y:0}, particles: 50, radius: 100, complete: function() {} },options); return this.each(function() { for(i=0;i<settings.particles;i++){ var particle = $("<div />").addClass(settings.particleClass); $(particle).css("position","absolute"); $(this).append($(particle)); $(particle).offset({ top:settings.origin.y-$(particle).height()/2, left:settings.origin.x-$(particle).width()/2 }); $(particle).animate( { "margin-top": (Math.floor(Math.random()*settings.radius)-settings.radius/2)+"px", "margin-left": (Math.floor(Math.random()*settings.radius)-settings.radius/2)+"px", "opacity": 0 }, { "duration": Math.floor(Math.random()*1000)+1000, "complete": function (){ $(this).remove(); } } ); } settings.complete.call(this); }); }; }(jQuery)); </script> <style> body{ background-color:black } .particle { width:8px; height:8px; background-color:red; } </style> </head> <body> </body> </html>
You can see it in action here:
Click on the black page to create an explosion made of 50 divs made with “particle” class. There also is space for some kind of customization, maybe I should improve a bit the plugin, but at the moment you can download the source code.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.