MooTools: Set Style Per Media

By on  

I'd bet one of the most used MooTools methods is the setStyle() method, which allows you to set CSS style declarations for an element. One of the limitations of MooTools' setStyle() method is that it sets the specific style for all medias. What if I want to set a style for only a specific media type? I've created a setStile() method that allows you to specify the media for which a style is set.

The MooTools JavaScript

	'setStile': function(key,value,media) {
		var style = $$('style[media=' + media + ']')[0];
		if(!style) {
			style = new Element('style',{
				'type': 'text/css',
				'media': media
		if(!this.get('id')) {
		style.set('text',style.get('text') + '#' + this.get('id') + '{ ' + key + ':' + value + '; }');
		return this;
	'setStiles': function(keyvalhash,media) {
		for(var key in keyvalhash) {
		return this;

Example Usages

$('nonoprint').setStile('border','1px solid #00f','print');
	'background-color': '#fffea1',
	'font-weight': 'bold',
	'opacity': '.5'

The Post-Use HTML View

<style type="text/css" media="print">
#nonoprint{ color:#f00; }
#nonoprint{ display:inline; }
#nonoprint{ border:1px solid #00f; }
#nonoprint{ background-color:#fffea1; }
#nonoprint{ font-weight:bold; }
#nonoprint{ opacity:.5; }

Obviously, as you can see from the Post-Use HTML, this isn't an elegant solution but it works in all browsers I tested except Internet Explorer. Hopefully a better solution is presented in the future.


Recent Features

Incredible Demos

  • iPhone Checkboxes Using&nbsp;MooTools

    One of the sweet user interface enhancements provided by Apple's iPhone is their checkbox-slider functionality. Thomas Reynolds recently released a jQuery plugin that allows you to make your checkboxes look like iPhone sliders. Here's how to...

  • CSS Vertical&nbsp;Centering

    Front-end developing is beautiful, and it's getting prettier by the day. Nowadays we got so many concepts, methodologies, good practices and whatnot to make our work stand out from the rest. Javascript (along with its countless third party libraries) and...

  • jQuery Link&nbsp;Nudging

    A few weeks back I wrote an article about MooTools Link Nudging, which is essentially a classy, subtle link animation achieved by adding left padding on mouseover and removing it on mouseout. Here's how to do it using...


  1. I’ve noticed that this code no longer works in IE8. This line seems to be causing the problems: style.set(‘text’,style.get(‘text’) + ‘#’ + this.get(‘id’) + ‘{ ‘ + key + ‘:’ + value + ‘; }’);

    Any ideas?

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

Use Code Editor