I have the following code which works, however event.srcElement
has been deprecated and I can’t get an alternative to work:
function logStats() {
switch (event.srcElement.id) {
case “stronglyAgree”:
stronglyAgree++;
break;
}
}
I’m using the i.d of the element that is clicked in order to keep a count of answers to a test.
The Mozilla docs say to use Event.target instead but replacing the above with the following doesn’t work whether I pass a prop to logStats() or not:
function logStats(e){
switch (e.target.id) {
case “stronglyAgree”:
stronglyAgree++;
break;
}
}
Does anyone have a current solution?
That probably has to do with React, or the framework you’re using, if the element has an id, and an event listener associated with it, then the code is correct.
I’d take a look at the event handling in react.
event.target.id should work
What is the full program code?
I’m not actually using React, just vanilla js.
When I mentioned props I actually meant parameters, sorry for any confusion.
@MarbledMinorMoth Then probably the element that is firing the event is not your previous srcElement.
Run the function like this:
function logStats(e) {
const myElement = e.target.id
switch (myElement) {
case 'stronglyAgree':
stronglyAgree++;
break;
}
}
and see if it is what you think
I managed to get the original code to work but only once I had added the last part:
function logStats(e){
switch (e.target.id) {
case “stronglyAgree”:
stronglyAgree++;
break;
}
}
const questionButtons = document.querySelectorAll(".questionButton"); // ADD EVENT LISTENER TO TRIGGER logStats()
questionButtons.forEach((item)=>{
item.addEventListener('click', logStats)
});
This allowed me to remove the original onclick function from each of the buttons that was previously handling everything.
system
Closed
July 20, 2022, 11:58pm
8
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.