Skip to content Skip to sidebar Skip to footer

How To Add Event Handler With Prototype New Element() Constructor?

I'm inserting an img tag into my document with the new Element constructor like this (this works just fine): $('placeholder').insert(new Element('img', {id:'something', src:myImage

Solution 1:

In this case, the best solution is to not use Prototype or at least not exclusively. This works:

var img = newElement('img',{id:'logo',alt:'Hooray!'});
img.onload = function(){ alert(this.alt); };
img.src = 'logo.jpg';

The key is setting the onload directly instead of letting Prototype's wrapper do it for you, and set the src last (actually not sure about that, but I do it last to be safe).

One-liners are overrated. With proper use of local variables the above is just as good. If you must have a one-liner, create a wrapper function or hack the Prototype core to ensure proper assignment (submit a patch!).

Solution 2:

Try

$('placeholder').insert(newElement("img", {
    id: 'something', 
    src:myImage
}).observe('load', function() {
    // onload code here
}));

Solution 3:

You might have to move the function elsewhere and call it by name

$('placeholder').insert(newElement("img", 
    {id:'something', src:myImage, onload:"javascript:moo()"}))

functionmoo() {
    alert("MOO");
}

Of course, because insert returns the element, you could inline Element.observe

$('placeholder').insert(newElement("img", 
    {id:'something', src:myImage})).observe('load', function(){alert("MOO")});

Solution 4:

The "onload" code shouldn't need to be wrapped up into an event handler. You are essentially loading the element right there, just put the code after the insert.

var img = newElement('img', {id: 'something', src:'myImage.jpg'});
$('placeholder').insert(img);
// Element has loaded! It can now be mucked around with.// The onload code goes here...

Solution 5:

It kind of sucks, but this is what you need to do:

$('placeholder').insert(newElement("img", {
    id:'something', src:myImage, onload:'alert("MOO")'
}));

The values in the attributes object just get inserted as strings, so when you do "onload: function() {...}" it turns into:

<imgonload="function() {...}" />

Which doesn't actually execute the code inside the function, it just defines a new anonymous function that won't execute unless you tell it to.


If you wanted to be a ninja about it, you could do something like this:

var moo = function() { alert("MOO"); };
$('placeholder').insert(newElement("img", {
    id:'something', src:myImage, onload:'(' + moo + ')()'
}));

Or even:

$('placeholder').insert(newElement("img", {
    id:'something', src:myImage, onload:'(' + function() { alert("MOO"); } + ')()'
}));

While kind of crazy, those options give you the actual function object to work with in case you need it.

Post a Comment for "How To Add Event Handler With Prototype New Element() Constructor?"