Wednesday 15 May 2013

javascript - Chrome Extension won't run function on button click -



javascript - Chrome Extension won't run function on button click -

i have code scrapes html of website on , copies clipboard. have working version copies text when click chrome icon, want add together several more options trying run script on button click within extension popup.

unfortunately, can not life of me manage happen on button click! when replace function alert("hi"), pops alert when click on extension icon rather button within popup. help!!!

class="snippet-code-js lang-js prettyprint-override">document.addeventlistener('domcontentloaded', function () { document.getelementbyid("full_team").addeventlistener('click', alert("hi"));; }); class="snippet-code-html lang-html prettyprint-override"><body> <h2>click re-create roster</h2> <button id="full_team">full team</button> <script src="event.js"></script> </body>

addeventlistener expects event name, , reference function should executed.

however, alert("hi") not reference function. statement executes alert, , returns undefined.

there 2 ways solve this:

for short functions should executed, can utilize anonymous function construct. statement

function(){ alert("hi"); }

does not execute alert, returns reference function execute alert when invoked. so, code becomes:

document.getelementbyid("full_team").addeventlistener('click', function() { alert("hi"); });

for longer functions, or functions can reused, create named function:

function sayhi() { alert("hi"); }

again, defines function, not execute it. then, can utilize name of function:

document.getelementbyid("full_team").addeventlistener('click', sayhi);

be sure pass reference function, , not execute it:

// wrong! document.getelementbyid("full_team").addeventlistener('click', sayhi());

speaking of reusing functions, suppose want create parameter-dependent function. instance, suppose want able "hi" various people depending on element pressed.

then, can go higher-level , create function returns function:

function sayhito(name) { homecoming function() { alert("hi, " + name + "!"); } } // here, invoking function correct: homecoming function document.getelementbyid("full_team").addeventlistener('click', sayhito("bob"));

javascript google-chrome-extension

No comments:

Post a Comment