Steal an inline onclick event from one element to another
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:
-
var oldItem = 'oldItem';
-
var itemToGetEvent = 'newItem';
-
var temp = $(itemToGetEvent).observe('click', function(){
-
eval($('oldItem').readAttribute('onclick'));
-
});
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:
-
<h1 onclick="this.innerHTML='foobar';">clickme</h1>
-
<h1>clickme2</h1>
-
<script>
-
var h = document.getElementsByTagName('h1');
-
h[1].onclick = function(ev) {
-
h[0].onclick.call(this, ev);
-
}
-
</script>
