Chrome Extension - js with parameters not working

I've been coding chrome extension popup with js that calls with a parameter.

here is html file

<!DOCTYPE html>
 <p id="demo">=a</p>
    <button type="button" id="do-count1">Count1</button>
    <button type="button" id="do-count2">Count2</button>  
  <script src="popup.js"></script>

since chrome extension js must be separated


var a=0;
 function count(k) {
     a = a + k;
     document.getElementById('demo').textContent = a;
document.getElementById('do-count1').onclick = count(2);
document.getElementById('do-count2').onclick = count(5);

when opening the popup window it gives 7, as those 2 functions executed automatically without clicking. further the buttons don't work.

a similar question was asked The Chrome extension popup is not working, click events are not handled

but my question one step advanced since i need to call js function with a parameter onclick.


Currently you're assigning a result of the function call, not a function reference.

Your options are:

  • use bind() to create a function wrapper that will pass the parameter:

    element1.onclick = count.bind(null, 2);
    element2.onclick = count.bind(null, 5);

    Note: this of the onclick function will be lost this way.

  • or use a simple function wrapper:

    element1.onclick = function() { count(2) };
    element2.onclick = function() { count(5) };

    Note: this of the onclick function will be lost this way, to preserve it:

    element1.onclick = function() {, 2) };
    element2.onclick = function() {, 5) };
  • use an HTML attribute:


    <button type="button" id="do-count1" data-add="2">Count1</button>
    <button type="button" id="do-count2" data-add="5">Count2</button>  


    function count() {
        document.getElementById('demo').textContent = a = a + this.dataset.add;
    element1.onclick = count;
    element2.onclick = count;

Need Your Help MVC3 getting checkbox value from HTML form

c# forms checkbox

I have a simple form in my MVC3 site that allows users to create a contest entry. This has been implemented and works fine currently, but a request has been made to now allow users to make their e...

Changing the Drop-down option based on the url from navigation menu

javascript jquery html css

I have a navigation menu on the top of my page. I am having four elements, in that if i need to select 'element1' it need to select the element1 , if I click 'option2' from navigation menu, it need...