Search code examples
javascriptimagethissrcconfirm

How i show image src on click


Write a function that will be called upon pressing the right button of one of the images you have on the site.
The function calls up a confirm () window in which you ask the user if he wants to know the source of the image
If the user clicks OK alert (this.src), which shows the content of the src attribute of that image
If the user clicks on cancel, disable the context menu that appears at pressing the right button

this is my wrong code

<img src="opera1.png" id="immagine1" alt="immagine1" width="500" height="333" oncontextmenu="destra()">
<img src="ioaparatissima.JPG" id="immagine2" alt="immagine2" width="500" height="333" oncontextmenu="destra()">

javascript

function destra(){
  var r = confirm("Vuoi conoscere la src dell'immagine");

  if(r == true) {
    alert(y.src);
  } else {
  }
}


Solution

  • i solved like this

    function destra(y) {
    
        window.addEventListener("contextmenu", function(e){e.preventDefault();}, false);
    
        var r = confirm("do you want to know the src of the image?");
    
      if(r == true) {
        alert(y.src);
      } else {
    
      }
    
    }
    <img src="https://picsum.photos/150" alt="immagine1"id="immagine1" alt="immagine1" width="150" height="150" oncontextmenu="destra(this)">
    <img src="https://picsum.photos/150" alt="immagine2" id="immagine2" alt="immagine2" width="150" height="150" oncontextmenu="destra(this)">