waleedd32
waleedd32

Reputation: 533

One function activated by two buttons

I have two buttons and one function called 'starta' and it has parameter 'oi'.

My question is shouldn't the button with id of 'ooii' just work and not both of them ? Could somebody explain the reason both of these buttons are working ?

function starta(oi) {
  document.getElementById(oi).style.backgroundColor = "green";
}
button.rond {
  width: 60px;
  height: 60px;
}
<table>
  <tr>
    <td class="np"><button style="background-color:yellow" id="y" class="rond" onclick="starta('y')">alotus</button></td>
  </tr>
  <tr>
    <td class="np"><button style="background-color:yellow" id="ooii" class="rond" onclick="starta('ooii')">alotus</button></td>
  </tr>
</table>

Upvotes: 0

Views: 74

Answers (3)

sina_r
sina_r

Reputation: 524

Basically what you are doing is , you are giving your function a parameter "oi"

        function starta(oi)

Then You you use that parameter as id:

        document.getElementById(oi)

Then you pass your function the value (argument) of the id of the actual button clicked and it becomes the parameter

        onclick="starta('ooii')"
        onclick="starta('y')

That basically means that you use the id "ooii" and "y" as your argument/value for your parameter.

if you click "y" your function looks like this:

function starta(y) {
document.getElementById(y).style.backgroundColor = "green";
        }

If you click "ooii" your function looks like this:

function starta(ooii) {
document.getElementById(ooii).style.backgroundColor = "green";
        }

Hope this helps :)

EDIT:

If you want only one button to work do:

 function starta() {
   document.getElementById("ooii").style.backgroundColor = "green";
    }

IN HTML:

onclick="starta()"

Upvotes: 1

Stratubas
Stratubas

Reputation: 3067

When you click the first button, starta is called with 'y' as the argument.

So starta finds the element with id equal to 'y' (it's the button you just pressed) and makes it green.

When you press the other button, it's the same thing but with with 'ooii' as the argument, so THAT button becomes green.


Edit: About your comment... Let's say you have this function:

function printThisArgument(myVariable) {
  console.log(myVariable);
}

When you do printThisArgument('hello'), the function will be called and its argument (myVariable) will have the value 'hello', so it will print "hello".

The name of the variable is irrelevant.

Upvotes: 1

T G
T G

Reputation: 501

While it's not clear what your intent was, your code works correctly as written.

The two buttons are independent, and when you click either one, the attached function runs and makes the background green. It happens to be the same function, and the parameter "oi" is closer to one name than the other, but that doesn't matter.

Upvotes: 0

Related Questions