Skip to content

Instantly share code, notes, and snippets.

@Nek-
Created March 1, 2013 16:08
Show Gist options
  • Save Nek-/5065650 to your computer and use it in GitHub Desktop.
Save Nek-/5065650 to your computer and use it in GitHub Desktop.
Make redirection to other pages with a select. Using mootools.
/**
* @author VEBER Maxime (Nek) <[email protected]>
* @company Wandi <www.wandi.fr>
* @requiremetns Mootools
* @compatibility IE7
*
* This script add to select the ability to redirect to another page.
*
*
* Usage:
* ======
*
* Imagine HTML like that:
* -----------------------
* <select class="selectToUrl">
* <option>Useless default option</option>
* <option class="url=[http://google.com]">Go to google !</option>
* </select>
*
* With that, you should use this JS:
* ----------------------------------
* new SelecRedirect();
*
* After DOM load, of course, but that's all.
*/
var SelectRedirect = new Class({
/**
* Initialize & build
*
* @param options Object
* @return void
* @see build method
*/
initialize: function (options) {
this.options = {
// Selector capable to get selects
'selector': '.selectToUrl',
// Option name in the class
'optionName': 'url'
};
this.options = Object.merge(this.options, options);
this.build();
},
/**
* Add events on selects
*/
build: function () {
$$(this.options.selector).each(function(el) {
// Add event
el.addEvent('change', this.redirect.bind(el, this.options));
}.bind(this));
},
/**
* Get the class, parse it and send to the good url.
*/
redirect: function (options) {
var exp = new RegExp('^' + options.optionName + '=\\[(.+)\\]$'),
classes = this.options[this.selectedIndex].get('class'),
match = null,
url = null;
classes = classes.split(' ');
classes.each(function(el) {
if(match = el.match(exp)) {
url = match[1];
return false;
}
});
if (url === null) return;
window.location = url;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment