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>
$("p").click( ... ), job done