Trying to add several functionalities with a single button using javascript
Hello guys, sorry to disturb you all; I'm trying to experiment with event bubbling but first I wanted to make a button that when I first click on it, some contents are added to my preformatted paragraph with id="output". Then when I clicked on it once more, the button content should change from "Click me ! " to "Reset" and it reset our preformatted paragraph content to an empty string. If I click on the "Reset" button now, I should have the "Click me!" button which display content of our preformatted paragraph as we were doing initially. I tried to do it inside the function handleClick itself, like I added the lines:
The problem is the browser is too fast, I can't see any change like we have the illusion that both events are happening "at the same time" . Can someone explain how I should tackle this problem please.
8 Replies
The problem is that I have 2 event listeners, one on the div element wrapping the button and the other one on the button itself. So the thing is when I click on the button, the 2 events are being fired so may be that's why the reset is happening instantaneously ?
I try to modify the code as above and it works fine. But, what if we have the same problem as earlier, like we have 2 event listeners with the same callback ?
here u dont even need to have an event listener on button
vause button is inside the wrapper
clicking the btn will also trigger click on the wrapper as the click happened within its bounding box
u might be in a situation where u have this wrapper and u have this button inside the wrapper and u want one thing to happen when u click the button but something else to happen when u click somewhere else other than the button but within the wrapper
in which case you will need to check, if the click was on the button or not
or simply if the button was clicked or not
also check out this
MDN Web Docs
Event: currentTarget property - Web APIs | MDN
The currentTarget read-only property of the Event interface identifies the element to which the event handler has been attached.
for experimental purpose here's a sample code from mdn
Yep I see
Current target is the current target being clicked then it propagates right? While target doesn't change, it is the element initially clicked and it is fixed
it's the target that changes
current target is the one that has the enent listener on
ahhh I see
yeah
thanks !
welcm