Treehouse

MooTools PulseFade Plugin

By on  

I was recently driven to create a MooTools plugin that would take an element and fade it to a min from a max for a given number of times. Here's the result of my Moo-foolery.

The MooTools JavaScript

var PulseFade = new Class({
			
	//implements
	Implements: [Options,Events],

	//options
	options: {
		min: 0,
		max: 1,
		duration: 200,
		times: 5
	},
	
	//initialization
	initialize: function(el,options) {
		//set options
		this.setOptions(options);
		this.element = $(el);
		this.times = 0;
	},
	
	//starts the pulse fade
	start: function(times) {
		if(!times) times = this.options.times * 2;
		this.running = 1;
		this.fireEvent('start').run(times -1);
	},
	
	//stops the pulse fade
	stop: function() {
		this.running = 0;
		this.fireEvent('stop');
	},
	
	//runs the shizzle
	run: function(times) {
		//make it happen
		var self = this;
		var to = self.element.get('opacity') == self.options.min ? self.options.max : self.options.min;
		self.fx = new Fx.Tween(self.element,{
			duration: self.options.duration / 2,
			onComplete: function() {
				self.fireEvent('tick');
				if(self.running && times)
				{
					self.run(times-1);
				}
				else
				{
					self.fireEvent('complete');
				}
			}
		}).start('opacity',to);
	}
});

Options of the class include:

  • min: (defaults to .5) the minimum opacity level
  • max: (defaults to 1) the maximum opacity level
  • duration: (defaults to 200) the length of time of the fade
  • times: (defaults to 5) the number of times the fade in/out should occur

Events of the class include:

  • onComplete
  • on Start
  • on Stop
  • onTick - Fires every time the fade reaches the fade reaches the min or max.

Sample Usage

window.addEvent('domready',function() {
	var pf = new PulseFade('pulse-fade',{
		min: .50,
		max: 1,
		duration: 400,
		onComplete: function() {
			alert('complete!');
		},
		onStart: function() {
			alert('started!');
		},
		onStop: function() {
			alert('stopped!');
		},
		onTick: function() {
			alert('tick!');
		}
	})
	
	$('stop-link').addEvent('click',function(e) { e.stop(); pf.stop(); });
	$('start-link').addEvent('click',function(e) { e.stop(); pf.start(); });
});

I'm satisfied with the effect by not the class as a whole. MooTools Core Developer and -More csar Aaron Newton frequently reminds me that a class needs to be as flexible and basic as possible. Unfortunately, this isn't as flexible of a class as it could be but it does the job.

ydkjs-3.png

Recent Features

  • Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an...

  • Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things...

  • How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to,...

Incredible Demos

  • Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the...

  • From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in...

  • Control Element Outline Position with outline-offset

    I was recently working on a project which featured tables that were keyboard navigable so obviously using cell outlining via traditional tabIndex=0 and element outlines was a big part of allowing the user navigate quickly and intelligently. Unfortunately I...

Discussion

  1. Nice plugin! I was thinking of writing something like this. You might want to consider including other options for tween, such as link because if I keep clicking on ‘start’ in your demo, it just totally messes the pulse.

  2. Hello David,

    Please try to use console.log in place of alert. (console.log is created by the firefox entension “firebug”).

    It is pretty nice, but i’m more like a jQuery man!

    // Alexander

  3. @Garrick: Good idea, I’ll check that out later.

    @Alexander: I’m aware of Firebug — what am I, a rookie? :) That’s just an example usage.

  4. Quit bring back the blink tag! :)

    I suffer from the same “keep the class generic” issue – but hey, it’s a journey, not a destination.

    @Alexander – console.log, being specific for Firebug, can create unneeded issues with example code (especially since most web developer blog audiences arrive on a plethora of browsers). Alert is generic and universal :)

  5. I hope the “webmasters” don’t get a hold of this…

  6. Mark Sanborn does not fear the reaper, but does fear the webmasters. I slay the webmasters.

  7. awesome !!!

  8. Well crap, the <marquee> worked in the preview of that ridiculous comment of mine…

    Anyway, this actually makes sense in some places: a recording indicator for time tracking, replacement for the ever-loved el.highlight(), or “new post” icons on a forum … lots of real uses.

    And of course the body tag could use some pulsing^^

  9. Nice Mooing. This post grabbed me as I worked out a Class with similar functionality for some months ago, always interesting to see different approaches and solutions.

    I remember that I also went with the opacity at first, but in IE6, it failed. Tried your demo in IE6 and found the same result (no pulsing). Not entirely impossible that it’s just a spook by my ie-browser (as I run IEs4Linux).

    So instead of the opacity property I used background-color. Now I know that this would not work with your demo as it pulses an image, but in my case, it fulfilled its task :]

    I cannot link to my Class, so I hope you don’t mind if I post my code in this comment.

    var Blinker = new Class({ // horrible name
    
        Implements: [ Options ],
    
        options: {
            color: '#fff', // fade to color
            duration: 500,
            times: 1 // how many blinks
        },
    
        initialize: function( target, options ){
            this.setOptions(options);
            this.target = $(target);
            this.target.store('nativeBg', this.target.getStyle('background-color'));
            this.fx = new Fx.Morph( this.target, { duration: this.options.duration } );
            this.count = this.options.times;
        },
    
        blink: function(){
            if( this.count > 0 ) {
              this.fx.start( { 'background-color': this.options.color } ).chain( function() {
                  this.fx.start( { 'background-color': this.target.retrieve('nativeBg') } );
              }.bind( this ));
              this.count--;
              this.blink.delay( this.options.interval * 2.2, this ); // 0.2 buffer
            } else {
                this.count = this.options.times; // reset
            }
        }
    });
    
  10. I was searching for

    < blink >

    alternative here, so how to rewrite this script to get pulsing without clicking start?

  11. merth

    hi devid big problem mootools help mi plase very plase :(

  12. I would be interested in pulse links
    how to that

    cordialement la france aka /fakessh/

  13. hi David :) thx for your works!

    I notice that with IE7 or 8, using this plugin fadeing an element like a div with some text in it, the text looks very strange while it is fadeing, it becomes irregular. This doesnt happen in FF.

    Any solution?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Use Code Editor