Here’s a nifty little trick that allows you to write “contextual” JavaScript. It’s incredibly obtrusive and probably shouldn’t be used at all but it’s still a pretty cool idea:
<div id="some-div"> <script type=":contextual"> alert(this.id); // "some-div" is alerted </script> </div> |
Instead of the this
keyword referencing the global object (window
) we can make it reference the parentNode
of the script element. Here’s the code that makes it work:
(function(){ var scripts = document.getElementsByTagName('script'), script, i = 0; while ( (script = scripts[i++]) ) { if ( /:contextual$/.test(script.type) ) { (new Function(script.innerHTML)).call(script.parentNode); } } })(); |
Take it or leave it! – I’m indifferent either way – yes, it’s obtrusive but you’ve got to admit, contextual JavaScript looks pretty neat!
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
Now that’s what I call “thinking outside the box”! Thumbs up for that (even though I agree it’s “incredibly obtrusive and probably shouldn’t be used at all”, it’s still very clever indeed).
ps: Why oh why did you change your blog’s design? I loved the previous one!
it’s this work well in all browsers?
/:contextual$/.test(script.type)
vs.':contextual' == script.type
?@Lea, I just felt it needed a change… I too have mixed feelings about this new design, I think I’ll stick with it for now though.
@test, yup 🙂
@joseanpg, I wanted it to support more explicit types, e.g.
Not a completely bad idea – I think this could be a useful approach in say some type of JavaScript templating markup for thick client apps