Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialmsdsmd sm,dfsadf
1,124 PointsWhy this does not work.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body><div style="height:200px;width:200px;background:red;"><button>JJJJJ</div>
<script>
const div = document.querySelector('div')
div.addEventListener('click',function(e){
if(e.currentTarget.tagName == 'DIV' ){
alert('asdssf')
}
})
</script>
</body>
</html>
/*
I trying to display message to the browser when
I click the parent element only, but why this won't.
Do I have to create event handler just for button to
stop it from bubbling or did I typed something wrong.
1 Answer
Jennifer Nordell
Treehouse TeacherHi there, msdsmd sm,dfsadf! If you're only wanting it to show when the div is clicked and not the button inside the div, then you need to use e.target
as opposed to e.currentTarget
. Because the button is inside the div the event bubbles up to the div when it is clicked which is where the event listener is attached, so it fires.
The answer is to make it so that you're using the event.target which tells us where the event started. So if the starting point was a DIV
and not a BUTTON
, then fire.
Hope this helps!