Reputation: 5
I have been trying to assign onclick events for multiple HTML
elements. I'm trying to make as little code as possible, by only using 1 function. I know a simple way to do it by adding event-attributes to the HTML elements, like this:
<body>
<p id="demo1" onclick="myFunc(this)">Paragraph 1</p>
<p id="demo2" onclick="myFunc(this)">Paragraph 2</p>
<script>
function myFunc(para) {
para.style.color = "red";
}
</script>
But if i were to add many event attributes to multiple HTML elements, the Html document would be a mess, right? so i would rather make the code in JavaScript. But the problem is that when i assign the code in Js, and click on one of the
tags, they both get triggered (btw, i am very new to coding i Js, so it might by my foolishness)
<body>
<p id="demo1">Paragraph 1</p>
<p id="demo2">Paragraph 2</p>
<script>
var x = document.getElementById("demo1").onclick = myFunc;
var y = document.getElementById("demo2").onclick = myFunc;
function myFunc() {
if (x == document.getElementById("demo1").onclick) {
document.getElementById("demo1").style.color = "red";
}
if (y == document.getElementById("demo2").onclick) {
document.getElementById("demo2").style.color = "red";
}
}
</script>
Upvotes: 0
Views: 2477
Reputation: 370689
Consider using event delegation instead - assign a listener to the container of the elements you want to listen for events on, and then check the event.target
(the clicked element that triggered the event) to see if it's an element you want the listener to run on:
document.body.addEventListener('click', ({ target }) => {
// Only continue on `<p>` elements:
if (!target.matches('p')) {
return;
}
target.style.color = 'red';
});
<p id="demo1">Paragraph 1</p>
<p id="demo2">Paragraph 2</p>
<div>some other element that will not change on click</div>
If you were to add listeners to each individual element, check this
inside the listener to refer to the element that was clicked, and then you can assign its style as desired:
document.getElementById("demo1").onclick = myFunc;
document.getElementById("demo2").onclick = myFunc;
function myFunc() {
this.style.color = 'red';
}
<p id="demo1">Paragraph 1</p>
<p id="demo2">Paragraph 2</p>
(you could also use a parameter in myFunc
to get the event
, and from that, the event.target
, just like in the first method)
Upvotes: 2
Reputation: 989
You can rely on event object to determine both the element which triggered the function, and the type of event (click, hover, key press, etc):
handleEvent({type}) {
switch(type) {
case "click":
return require("./actions/doStuff")(/* action dates */)
case "mouseenter":
return this.setState({ hovered: true })
case "mouseleave":
return this.setState({ hovered: false })
default:
return console.warn('No case for event')
} }
Upvotes: 0
Reputation: 221
jQuery would be an option.
$(document).on('click','p',function(){
$(this).css('color','red');
});
Upvotes: 1