Vanilla Javascript.fadein (). FadeOut () without jQuery

I am developing for IE10 +, so I decided not to use jQuery. I am writing a custom javascript function to select, Fadein, FadeOut, etc., and it works fine. but I like to use a jQuery-style function (Object.fadeIn (), Object.FadeOut (), etc.).

Instead of the jQuery Selector, I use this.

function _(el){ return document.getElementById(el); } 

When I need to select a Dom object, I use this.

 var myButton = _("button"); 

When I need fadeIn or fadeOut any object, I use this.

 function fade(type, ms, el) { var isIn = type === 'in', opacity = isIn ? 0 : 1, interval = 50, duration = ms, gap = interval / duration; if(isIn) { el.style.display = 'inline'; el.style.opacity = opacity; } function func() { opacity = isIn ? opacity + gap : opacity - gap; el.style.opacity = opacity; if(opacity <= 0) el.style.display = 'none' if(opacity <= 0 || opacity >= 1) window.clearInterval(fading); } var fading = window.setInterval(func, interval); } 

Here is a specific code to redeem my button

 fade('out', 500, myButton); 

I like to use this as _( "myButton" ).fadeIn( 100 );

Update: The trick was to use the prototype function for "-" to add additional ones such as fadein (), fadeOut ().

+5
source share
1 answer

This will do the trick:

 function _(el) { if (!(this instanceof _)) { return new _(el); } this.el = document.getElementById(el); } _.prototype.fade = function fade(type, ms) { var isIn = type === 'in', opacity = isIn ? 0 : 1, interval = 50, duration = ms, gap = interval / duration, self = this; if(isIn) { self.el.style.display = 'inline'; self.el.style.opacity = opacity; } function func() { opacity = isIn ? opacity + gap : opacity - gap; self.el.style.opacity = opacity; if(opacity <= 0) self.el.style.display = 'none' if(opacity <= 0 || opacity >= 1) window.clearInterval(fading); } var fading = window.setInterval(func, interval); } _('myButton').fade('out', 500); 

Now you can expand your object _ any function like jQuery.

+7
source

All Articles