Steal an inline onclick event from one element to another

2009 March 26

Sometimes, someone writes a piece of HTML with inline JS (naughty naughty). And sometimes, you need to use that same functionality elsewhere in your document, but it is named dynamically so you can’t just copy/paste.

Here comes Prototype to the rescue.

You can do this:

  1. var oldItem = 'oldItem';
  2. var itemToGetEvent = 'newItem';
  3. var temp = $(itemToGetEvent).observe('click', function(){
  4.    eval($('oldItem').readAttribute('onclick'));
  5. });

olditem is the item that has the onclick attribute inline
newitem is the item that needs to get this onclick attribute

I am just copying the code and then setting a listener on the new item so that it mimics the onclick attribute of the other item.

Another Suggestion:

  1. <h1 onclick="this.innerHTML='foobar';">clickme</h1>
  2. <h1>clickme2</h1>
  3. <script>
  4.  var h = document.getElementsByTagName('h1');
  5.  h[1].onclick = function(ev) {
  6.    h[0].onclick.call(this, ev);
  7.  }
  8. </script>
Sphere: Related Content

2 Comments leave one →
2009 March 26

You could also just call the onclick attribute as a function – it’s actually stored as a function.

If you need to modify the scope of it, you could use call – something like this http://codeutopia.net/files/inline.html

(Not tested in IE)

2009 March 26

That is a really cool way to do exactly the same thing I am doing with a little less code. I am including this in the post above.

Thanks Jani!

Leave A Comment

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS