0

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>
3
  • 1
    onclick is a very old-fashioned way of assigning javascript events. You're much better off using addEventListener() Commented Jan 9, 2019 at 12:32
  • If including jQuery is an option : $("p").click( ... ), job done Commented Jan 9, 2019 at 12:34
  • The reason why your code always changes the color of both elements is because of the if statements in the myFunc function. The conditions always resolve to true .. Look at the answers below for a better option. Commented Jan 9, 2019 at 12:43

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

That last sentence gave me an idea! i made a function, and assigned the <p> tags to it, and added this code into the function: event.target.style.color = "red"; it works like a charm!
1

jQuery would be an option.

$(document).on('click','p',function(){
   $(this).css('color','red');
});

2 Comments

Or simply $("p").click( ... ) if event delegation is not necessary (if <p>s are static and not dynamically added)
@JeremyThille I like the dynamically added elements. It's safer against click bot's and automated processes.
0

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') } }

1 Comment

Thanks for helping, found a tiny bit simpler way to do my task, but this might come in handy to :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.