Событие 'click' не срабатывает на вложенном в элемент тексте
Мне нужно сделать, чтобы при нажатии на круг срабатывало событие "click". Но оно отрабатывает только за границами надписи "Нажмите на кнопку". Я делаю это через делегирование. Навешиваю класс на весь документ и потом через event.target.className проверяю условие: если это "circle" , тогда выведи alert. Но я не понимаю,почему не срабатывает на тексте. Спасибо за ответ.введите сюда код
function clickFunction(event) {
if (event.target.className == 'circle') {
alert('нажал')
}
}
document.addEventListener('click', clickFunction);
.circle {
width: 100px;
height: 100px;
background-color: aquamarine;
color: black;
border-radius: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
font-size: 14px;
text-align: center;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
<div class="circle">
<span class="circle__text">Нажмите на круг</span>
</div>
Ответы (2 шт):
function clickFunction(event) {
console.log(event.target.className);
if (event.target.className == 'circle') {
alert('нажал')
}
if (event.target.className == 'circle__text') {
alert('нажал circle__text')
}
}
document.addEventListener('click', clickFunction);
.circle {
width: 100px;
height: 100px;
background-color: aquamarine;
color: black;
border-radius: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
font-size: 14px;
text-align: center;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
<div class="circle">
<span class="circle__text">Нажмите на круг</span>
</div>
а лучше event.target.className.includes('circle__text') потому что классов может быть несколько
А если в "circle" будет множество вложенных элементов. Мне для всех условия прописывать?
В данном случае вам понадобится 'closest', который возвращает ближайший родительский элемент. А для понимания природы клика рекомендую — Всплытие и погружение.
function clickFunction(event) {
if (event.target.closest('.circle')) {
console.log('.circle');
} else {
alert('Упс — мимо.)')
}
}
document.addEventListener('click', clickFunction);
.circle {
width: 100px;
height: 100px;
background-color: aquamarine;
color: black;
border-radius: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
font-size: 14px;
text-align: center;
}
.square {
width: 70px;
height: 70px;
background-color: grey;
}
.circle_small {
width: 70px;
height: 70px;
background-color: white;
border-radius: 50%;
}
.text {
font-family: sans-serif;
font-size: 10px;
line-height: 12px;
display: inline-block;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
<div class="circle">
<div class="square">
<div class="circle_small">
<span class="text">Нажмите куда попало в области большого круга</span>
</div>
</div>
</div>