Search code examples
javascriptbookmarklet

Bookmarklet containing a button


I'm trying to create a bookmarklet that, when clicked, displays a search panel (i.e. a text input and button) on the page. In the text input one can enter a dom element Id and after clicking the search button, it will find the first element matching the Id entered into the search field. My problem is that I don't know how to add an onclick attribute to the button and then successfully call the corresponding function. Here's my code:

javascript:(
    function(){

        var disIPanel = document.getElementById('disappearioPanel');
        if(!disIPanel) {
            disIPanel = document.createElement('div');
            disIPanel.setAttribute('id', 'disappearioPanel');

            var disITxt = document.createElement('input');
            disITxt.setAttribute('type','text');
            disITxt.setAttribute('id', 'disappearioText');

            var disSBtn = document.createElement('button');
            disSBtn.innerHTML = 'Search';
            disSBtn.setAttribute('type', 'button');
            // Here I add my 'onclick' attribute, if this is not the best way to go 
            // about it, please let me know
            disSBtn.setAttribute('onclick', 'doThing()');

            disIPanel.appendChild(disITxt);
            disIPanel.appendChild(disSBtn);

            document.body.appendChild(disIPanel);
        } else {
            disIPanel.parentNode.removeChild(disIPanel);
        }
        // Here I've tried `function doThing() {...}` and `var doThing = function() {...}`
        // But neither ways of declaring/calling my function works
    }
    // Here I've tried `function doThing() {...}` and `var doThing = function() {...}`
    // But neither ways of declaring/calling my function works
)();

Questions

  1. How/Where do I declare the function that I'm trying to call when clicking the button.
  2. Can the onclick attribute actually call any function the way it currently is and, if not, how do I go about calling my function?

Currently

  1. The bookmarklet successfully displays the search panel when called so there's no issue there
  2. When I declare the function immediately after the if statement and then click the Search button, I get the error Uncaught ReferenceError: doThing is not defined
  3. When I declare the function outside the wrapper function, I get the error Uncaught SyntaxError: Unexpected token function

Solution

  • Functions called from onclick attributes have to be in the global scope. All the code in your bookmarklet is in the scope of your IIFE. You could make it a global name with:

    window.doThing = function() {
        ...
    };
    

    Or you can define the function normally, and use addEventListener instead of the onclick attribute:

    disSBtn.addEventListener("click", doThing);