P
P
pasha_hp2020-05-07 12:29:09
JavaScript
pasha_hp, 2020-05-07 12:29:09

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

2 answer(s)
E
Eugene, 2020-05-07
@pasha_hp

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>

I
Ihor Bratukh, 2020-05-08
@BRAGA96

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question