Search code examples
javascriptprototypejs

Prototype JS: Document.observe fires "undefined is not a function" error


I try to use the Event.observe method which is provided by Prototype JS. To be sure that the DOM is loaded, I use document.observe. This causes the error Uncaught TypeError: undefined is not a function. Prototype JS was loaded as you can see below:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>playground</title>
    <script language="javascript" type="text/javascript" src="../js/prototype.js"></script>
    <script language="javascript" type="text/javascript" src="../js/functions.js"></script>
</head>

<body>
    <div>
        <a href="#" id="meinLink">Hello World</a>
    </div>
    <input type="button" onclick="changeLinkText()" value="Change link by using Prototype">
</body>

JavaScript

//this works
var changeLinkText = function(){
    $("meinLink").innerHTML="prototypeWorks";
};

//this causes the error
Document.observe("dom:loaded", function() {
    $("meinLink").observe('click', function(e) {
        document.getElementById('meinLink').innerHTML="prototypeDoesntWork";
    });
});

Solution

  • Your D in

    Document.observe("dom:loaded", function() {
    

    is upper-case, fixing it to it's correct notation

    document.observe("dom:loaded", function() {
    

    will probably do the job.

    You can also try to invoke an on-click-event listener.

    $$('meinLink').invoke('on', 'click', '.item', function(event, el) {
        // el is the 'meinLink' element
    });
    

    It's even possible that just using on will do the job.

    $("meinLink").on("click", function(event) {
       document.getElementById('meinLink').innerHTML="prototypeDoesntWork";
    });