Answer the question
In order to leave comments, you need to log in
How to hang an event on a picture returned by a function?
Hi all.
I have a function that returns html markup. Inside this markup there is an image. How can I put a click on this picture?
const showJoke = (id, category, joke, updated) => {
return `
<div class="joke">
<div class="joke__id">
id: <a href="https://api.chucknorris.io/jokes/${id}">ID: ${id}</a><img src="../link.png" alt="">
</div>
// на эту картинку нужно повесить событие
<img class="img" src="https://img.icons8.com/ios/50/000000/like.png">
//
<div class="joke__text">
${joke}
</div>
<div class="joke__info">
<div class="info__updated">
Last update: ${updated} hours ago
</div>
<div class="info__category">
${category}
</div>
</div>
</div>
`;
};
Answer the question
In order to leave comments, you need to log in
Use document.addEventListener
<!doctype html>
<html>
<head>
</head>
<body>
</body>
<script>
document.addEventListener("click", (event) => {
if (event.target.className === 'img') {
alert('click on img');
}
});
const showJoke = (id, category, joke, updated) => {
return `
<div class="joke">
<div class="joke__id">
id: <a href="https://api.chucknorris.io/jokes/${id}">ID: ${id}</a><img src="../link.png" alt="">
</div>
// на эту картинку нужно повесить событие
<img class="img" src="https://img.icons8.com/ios/50/000000/like.png">
//
<div class="joke__text">
${joke}
</div>
<div class="joke__info">
<div class="info__updated">
Last update: ${updated} hours ago
</div>
<div class="info__category">
${category}
</div>
</div>
</div>
`;
};
const html = showJoke('id', 'category', 'joke', 'updated');
document.body.insertAdjacentHTML('afterbegin', html);
</script>
</html>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question