Search code examples
javascriptsyntaxuserscripts

My userscript doesn't work and I don't know why (overuse of var keyword)


Hey guys/gals I just discovered the dopeness that is userscripts and I wanted to create one. from the limited amount of tutorials online I managed to come up with this.

// ==UserScript== 
// @name My add on
// @description A script that adds a green div to the bottom of the page 
// @include http://*
// @grant none
// ==/UserScript== 
function createDiv(){
var userBar=document.createElement('DIV');
var userBar.style.height='80px';
var userBar.style.width='100%';
var userBar.style.backgroundColor='green';
document.body.appendChild(userBar);
}
createDiv();

This is just a test script that adds a green div to the bottom of the page. Unfortunately, it does nothing when implemented.


Solution

  • The issue is caused because you write always the var in front. You can only do that during declaration.

    This is correct:

    function createDiv(){
        var userBar=document.createElement('DIV');
        userBar.style.height='80px';
        userBar.style.width='100%';
        userBar.style.backgroundColor='green';
        document.body.appendChild(userBar);
    }
    
    createDiv();
    

    Additionally, since you said you want to add it at the bottom of the site, you might add before adding the element to body:

    userBar.style.position='absolute';
    userBar.style.bottom='50px';