I've wrote about how to extend the class creation (Binds and Exposes mutator) and implement a custom Event (outerClick). In this post I'll show you the creation of custom CSS pseudo selectors to use in any MooTools CSS based selector (for example with $$ or getElement). Note, that these Selectors are fully cross browser. (Sure thing you can't use them inside your CSS files.)
MooTools already includes most of the CSS3 pseudo selectors (:nth-child, :contains, and :not to name a few examples).
To add your own pseudo selector you have to add it as a function to Selectors.Pseudo. Two arguments will be passed to the function. First argument is the parameter given to pseudo selector in the form :pseudo(parameter) or undefined if none given. The second argument is an object in which you can store temporary data for following elements visited during the traversing of one selector. This is used for example in the :nth-child pseudo selector. The actual element being filtered is available as the scope of that function (this). The function should return true when the element is matched by the pseudo or false otherwise.
To show you the usage I'll create a simple pseudo selector, :random, with probably little practical use. It will have an optional parameter for the probability to select the element with a default value of 0.5 (50%).
Selectors.Pseudo.random = function(probability, local){ return Math.random() < (probability || .5).toFloat(); }; // selects half of the divs on average $$('div:random'); // selects 20% of the h2 elements with class article on average $$('h2.article:random(.2)');
Note, that the element bound to the filter is not extended for performance reasons. That means if you want to use a Element method inside the filter, say getStyle, this.getStyle(style) doesn't work. You'd have to extend the this with $. For example: $(this).getStyle(style).
But this would cause each element inspected to be extended. To increase the speed of the pseudo selector generics can be used on the unextended Element: Element.getStyle(this, style).
Hi Jan,
I didn't understand the last paragraph. Could you elaborate a bit ? Is it a problem with the particular psuedo filter you just implemented, or is it a general thing for all psuedo-selectors ?
That's a "problem" of every pseudo selector or speed critical function. I've modified the last paragraph to make it a bit more clear, but I didn't want to write much about generics here. Probably that's going to be one of my next articles.
...click="javascript:pageTracker._trackPageview ('/outbound/blog.kassens.net');">Jan Kassens about how to create a custom pseudo selector in MooTools. I was surprised at the ease in which one can add their own pseudo selector that I thought I’...
I still do not really understand the last paragraph and if you ever write more about this topic it would be awesome if you could elaborate on this more because i am currently doing something with this.