Michal Kotus
Michal Kotus

Reputation: 157

use the same javascript for different div

I have got something like:

<div id="div1"><?php include 'test.php'; ?></div>
<div id="div2"><?php include 'test.php'; ?></div>

and test.php is:

<button onclick="myFunction()">test</button>

How can I invoke myFunction separately for div1 and div2? I mean, if I click on the button in div1, myFunction is done only in that div. I found this javascript keyword, but I can not apply it correctly.

No jQuery please.

Upvotes: 0

Views: 144

Answers (4)

codebytom
codebytom

Reputation: 448

Check the below code

<button onclick="myFunction.bind(this)">test</button>

Upvotes: 0

Seimen
Seimen

Reputation: 7250

Here's one solution:

function myFunction(ev) {
	console.log(ev.target.parentNode.id);
}
<div id="div1">
  <button onclick="myFunction(event)">button 1</button>
</div>
<div id="div2">
  <button onclick="myFunction(event)">button 2</button>
</div>

You can pass in the event object through which you then receive the clicked target and and its parentNode, i.e. the corresponding div.

Upvotes: 1

Exiam
Exiam

Reputation: 91

You can pass the context to your function with the call method, like this :

<button onclick="myFunction.call(this)">test</button>

Then, in your function, you can retrieve the div element by using this.parentElement.

function myFunction() {
  document.getElementById('result').innerHTML = this.parentElement.id;
}
<div id="div1"><button onclick="myFunction.call(this)">test</button></div>
<div id="div2"><button onclick="myFunction.call(this)">test</button></div>

<div id="result"></div>

Upvotes: 1

Nico_
Nico_

Reputation: 1386

You can add a parameter in your function.

<div id="div1"><?php $button=1; include 'test.php'; ?></div>
<div id="div2"><?php $button=2; include 'test.php'; ?></div>

and your php:

<button onclick="myFunction(<?php echo $button;?>)">test</button>

So now you can use that parameter to know which button has been pressed.

Upvotes: 1

Related Questions