skip to Main Content

I am trying to make it so that an alert pops up when you click the image but for some reason it doesn’t work and tells me I need to put a ")" even though one is already there. Someone pls help.

 <img src="descarga (3).png" height="20">
        <button 
        onclick=(alert('yay you clicked'))
        >
            click me!! </button>

4

Answers


  1. You need to add " around the js function in the declaration of onclick.

    Something like :

     <button onclick="myFunction()">Click me</button> 
    

    Please see : event onclick doc

    Login or Signup to reply.
  2. You need to add the listener to the image itself and not a button.

    const img = document.querySelector('#some_img');
    img.addEventListener('click', () => alert('Hello World!'));
    <img id='some_img' src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fimages.freeimages.com%2Fimages%2Flarge-previews%2F43d%2Fdummy-1536702.jpg&f=1&nofb=1&ipt=e4d5a59257d3771e098561d3e2d0fb317319369a3546b1d8d5f1576cbc5d61eb&ipo=images" height="100"/>
    Login or Signup to reply.
  3. Syntax Error – use "" instead ()

    <button onclick="alert('yay you clicked')">click me!!</button>
    
    Login or Signup to reply.
  4. If you want to display alert on image you need to add onclick in image and also wrap alert in ""

    <img src="https://cdn-icons-png.flaticon.com/512/3048/3048127.png" height="40" onclick="alert('yay you clicked')" >
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search