1

I am writing a UserScript, everything works fine until now, just when I click on a button I applied an onClick Attribute on, the console keeps telling me Uncaught ReferenceError: SB_Change is not defined and the function SB_Change(what) will not be executed.

Code:

window.addEventListener('load', function() {
    var but1 = document.createElement("BUTTON");
    var t1=document.createTextNode(" + ");
    but1.style.width = "16px";
    but1.style.height = "16px";
    but1.appendChild(t1);
    but1.setAttribute('onclick','SB_Change("+")');
    // -
    var but2 = document.createElement("BUTTON");
    var t2=document.createTextNode(" - ");
    but2.appendChild(t2);
    but2.style.width = "16px";
    but2.style.height = "16px";
    but2.setAttribute('onclick','SB_Change("-")');
    // -
    var SB_text = document.getElementById("shoutbox").getElementsByTagName("h3")[0];
    SB_text.innerHTML = "Shoutbox ";
    SB_text.appendChild(but1);
    SB_text.appendChild(but2);

    function SB_Change(type){
        var H = document.getElementById("sbPosts").maxHeight;
        switch(type){
            case "+":
                H = "800px";
                break;
            case "-":
                H = "400px";
                break;
        }
    }
}, false);
Brock Adams
  • 90,639
  • 22
  • 233
  • 295

1 Answers1

0

Two problems:

  1. Function SB_Change is defined inside the load-function scope. By the time you click on a link, this scope no longer exists.
    Move the definition to outside the load handler, like so:

    window.addEventListener ('load', function () {
        ... ...
    }, false);
    
    function SB_Change (type){
        ... ...
    }
    
  2. Otherwise, this question is a duplicate of Uncaught ReferenceError: function is not defined with onclick .
    Userscripts are sandboxed unless (a) you deliberately inject the code or (b) use @grant none mode on those engines that support it. (Neither of these modes is recommended unless absolutely, positively necessary.)

    Don't use onclick (¡ever!). See the duplicate question.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • Thank you, I did like you said but it dont work. Maybe because my function got an argument? Anyways heres me new code: http://pastebin.com/LQmn1NEr It doesn't tell me "SB_Change is not defined..:" anymore when I click on a button, it just does nothing and when I enter SB_Change("+") into the console, than it states that SB_Change is not defined –  Sep 05 '14 at 18:15
  • That new code uses `addEventListener` improperly. Also, in general, you can't use userscript functions from the console. But, in this case you could by defining it like: `window.SB_Change = function (type){`. ... Anyway, you need to open a new question for these new problems. – Brock Adams Sep 05 '14 at 23:43