h

Loading...

 

Tuesday, March 30, 2010

auto-linking with mootools

I hate doing things more than, let's say, twice. So I decided to do this little snippet to simplify linking inside articles.
preparation
First I've defined an object containing all often-used links I want to get replaced. Shortnames as key, display-name and link as value-array.

var linkObj = {
 // these here are for my special needs. Modify them matching yours.
 // syntax
 // 'short name': ['display name', 'http://link-adress']
 'moo': ["mootools", "http://mootools.net"], 
 'core': ["mootools.core", "http://mootools.net/core"],
 'more': ["mootools.more", "http://mootools.net/more"],
 'cufon': ["cufón", "http://cufon.shoqolate.com/generate/"],
 'lighter': ["lighter.js", "http://pradador.com/code/lighterjs/"],
 'pjs': ["processing.js", "http://processingjs.org/"]
};
The auto-link-element have to be placed in the text where needed. The element-text should correspond to a key in the defined linkObj-var.

<a class="auto">core</a>

<a class="auto" title="→ mootools.core" href="http://mootools.net/core" target="_blank">mootools.core</a>
note: these values match my linkObj-var.
the replacement-function
This function connects the text inside the found links with the corresponding key-value-pair inside the defined linkObj.

var autoLinker = function (links) {
 $each(links, function (link) {
  link.set({
   'href': linkObj[link.get('text')][1],
   'text': linkObj[link.get('text')][0],
   'title': '\u2192 ' + linkObj[link.get('text')][0],
   'target': '_blank'
  })
 });
}
a little moooh
Search for replacement elements and if found replace them. The $$('a.auto') catches all the links and then we send them to the autoLinker-function.

// domready
window.addEvent('domready',function() {
 if ($$('a.auto').length) {autoLinker($$('a.auto'))};
}); // end domready
the complete code

var linkObj = {
 // replace with key-value pairs that match your needs
 'moo': ["mootools", "http://mootools.net"], 
 'core': ["mootools.core", "http://mootools.net/core"],
 'more': ["mootools.more", "http://mootools.net/more"],
 'cufon': ["cufón", "http://cufon.shoqolate.com/generate/"],
 'lighter': ["lighter.js", "http://pradador.com/code/lighterjs/"],
 'pjs': ["processing.js", "http://processingjs.org/"]
};

var autoLinker = function (links) {
 $each(links, function (link) {
  link.set({
   'href': linkObj[link.get('text')][1],
   'text': linkObj[link.get('text')][0],
   'title': '\u2192 ' + linkObj[link.get('text')][0],
   'target': '_blank'
  })
 });
}

// domready
window.addEvent('domready',function() {
 if ($$('a.auto').length) {autoLinker($$('a.auto'))};
}); // end domready

s
Is that something that's worthy converting to a mootools-class? For my taste it's too simple, just standard-knowledge. What do you think? Let me know.
requires: core

No comments:

Post a Comment