0

Hello I have the following code:

<img alt="image321" onclick="image(//here i want to pass the alt attribute to my function Bild()//);" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />


<script>
        function image(alt){
            
            alert(alt.src);
            
        }
</script>

I have my image and have given it an alt attribute with the value "image321".Now I want to pass this value to my function image() and output the value with alert as soon as I clicked on the image. But the output is always undifined. Could someone please help me how to solve this problem. Many greetings Nils

3 Answers3

2

First thing would be to avoid inline handlers - they have quite a few problems, too many to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with addEventListener instead.

Inside the listener, reference this to get to the clicked element, and its src property to get to its src:

document.querySelector('img').addEventListener('click', function() {
  console.log(this.src);
  console.log(this.alt);
});
<img alt="image321" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You should try using this, which sends the element that you run the function with.

Here is an example:

function image(alt) {
alert(alt.src);
}
<img alt="image321" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" onclick="image(this)"/>
0

function myfunc(img){
            
            alert(img.alt);
            
        }
<img alt="image321" onclick="myfunc(this);" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />
Mehrzad Tejareh
  • 635
  • 5
  • 21