Search code examples
javascripthtmlfunctioneventsborder

give each picture a border on click


I want to give a picture a border. But there are multiple pictures and only the ones I click on should get a border. iI could just give every picture a single ID and write a script for each but that would be too much since there are more pictures coming. I've tried multiple things, but right now the code looks like this:

<!DOCTYPE html>

<!-- ... -->

<div>
    <img src="Champs/Vayne.png" class="vayne">
    <img src="Champs/Nasus.png" class="nasus">
</div>
<!-- ... -->

<script>

function Border()
{
    document.querySelector(".vayne").addEventListener("click", function changeBorder
    {
        changeBorder.target.style.border = "solid";
    });
}

</script>

I've tried to have the background change to red instead so I guess there must be a mistake in the line with the event listener but I don't know what's wrong there.


Solution

  • This adds a border to the image when you click on the image: we create a function that adds a border to an element, and we call it when an element gets clicked (with onclick)

    <img src="Champs/Vayne.png" onclick="mark(this)">
    
    function mark(el) {
        el.style.border = "1px solid blue";
    }
    

    http://jsfiddle.net/8QGkq/