Home > Net >  onClick event on the anchor/ image tag html
onClick event on the anchor/ image tag html

Time:10-27

I have numerous small images, which I am rendering using HTML. When a user clicks on the image, they are next opened in modal body in big size. Since I need to dynamically change the content of modal body e.g. when Picture1.jpg is clicked, modal body should include picture1.jpg and vice versa.

However, I am not sure, how do I trigger onclick event on <a> tag or <img> tag to obtain some information that helps me to identify which image was clicked.

<a href="images/Picture1.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
    <img src="images/Picture1.jpg" alt="image not available">
</a>
<a href="images/Picture1.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
    <img src="images/Picture2.jpg" alt="image not available">
</a>

Modal

<div class="modal-body">
       <img src="images/Picture1.jpg" alt="image not available" id="imagepreview" style="width:100%; height: 100%;" >
</div>

CodePudding user response:

You can use event.target in plain javascript and $(this) if you want to use Jquery.

//Plain Javascript
document.getElementsByTagName('img')[0].addEventListener("click", function(event) {
  console.log(event.target.src);
});

//Jquery
$('img').click(function() {
  console.log($(this).attr('src'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src="https://picsum.photos/200">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I would use a Button since you aren't actually linking, you're performing a JS function. Then I'd add an event listener to the buttons that updates the target images src based on the button's data-src value.

const buttonList = document.getElementsByClassName('target-button');
const modalImg = document.getElementById('imagepreview');

const processImg = (imgSrc) => () => {
  modalImg.src = imgSrc;
};

Array.from(buttonList).forEach((button) => {
  const buttonImgSrc = button.dataset.src;
  button.addEventListener('click', processImg(buttonImgSrc))
});
<button class="target-button" data-src="images/Picture1.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
    <img src="images/Picture1.jpg" alt="image not available" />
</button>
<button class="target-button" data-src="images/Picture2.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
    <img src="images/Picture2.jpg" alt="image not available" />
</button>

<img src="" alt="image not available" id="imagepreview" style="width:100%; height: 100%;" />
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related