Chaining functions in Javascript
Most of us are aware of the all famous Jquery demo
$("p.neat").addClass("ohmy").show("slow");
There are many resources out their on which demonstrates various ways of chaining javascript function but, I always like to explore my own ways of doing things, let people call it re-inventing the wheel, but like doing that I like to make my own wheel! [ Enough of Nihilism! ]
Below is a simple code that /me managed to pull, which is closest to the Jquery demo and as always there might be better ways of doing the same, do let me know your way of doing this.
$ = (function (document) { var self = ''; return { get: function (selector) { self = document.querySelector(selector); return this; }, addClass: function (new_class) { self.classList.add(new_class); return this; }, show: function () { var displayVal = window.getComputedStyle(self).display; if(displayVal === 'none') self.style.display = "inherit"; return this; }, hide: function () { var displayVal = window.getComputedStyle(self).display; if(displayVal !== 'none') self.style.display = 'none'; return this; }, toggle: function () { var displayVal = window.getComputedStyle(self).display; displayVal !== 'none' ? self.style.display = 'none' : self.style.display = "inherit"; return this; } }; }(document));
P.S : Thanks to ImBcmDth for suggesting, window.getComputedStyle(self).display;
With this one can do something like : $.get('p.neat').addClass().show()
Recent blog posts
- watir-webdriver web inspector
- gem list to gemfile
- Packing ruby2.0 on debian.
- Made it into The Guinness Book!
- to_h in ruby 2.0
- Filter elements by pattern jQuery.
- Better HTML password fields for mobile ?
- Grayscale image when user offline
- nth-child CSS pseudo-class Christmas colors
- EventEmitter in nodejs