I have few images and when clicked, I want to run code, let's say alert image number.
<img onclick="picture(1)" src="asd.jpg">
<img onclick="picture(2)" src="sdf.jpg">
<script>
function picture(picnumber){
alert(picnumber);
}
</script>
It worked, when I was alerting string, not variable.
Edit: I'm sorry for including example and not my actual code, I thought it was ok, solution given below however didn't fix my code:
<body>
<style>
img{
height:80px;
}
</style>
<script>
function picture(picbumber){
alert(picnumber);
}
</script>
<h1>GALLERY</h1>
<div class="photos">
<img onclick="picture(1)" src="https://i.insider.com/5f5a5f37e6ff30001d4e8163?width=700"/>
<img onclick="picture(2)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSChu52FnNKfSPRTMY8HIXei8leVAMvkURqqQ&usqp=CAU">
<img onclick="picture(3)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSIvgVWXKciw_UZIuzVenY4QvmCbDQb43J1lQ&usqp=CAU">
<img onclick="picture(4)" scr="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSY9xhvbRt8gXsEyO1dOW41asBHrEb2mZkRgQ&usqp=CAU">
<img onclick="picture(5)" src="https://dkt6rvnu67rqj.cloudfront.net/cdn/ff/T8cy0-640W8sartvA9TWmv08NbGPFxsVvf8gFtBDE08/1577112797/public/styles/600x400/public/media/int_files/elephant_in_tanzania.jpg?h=f507d761&itok=Ei8OXcGi">
<img onclick="picture(6)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1u8AKJBUZdSX7SIHvd8R1SiYyypx7elpstQ&usqp=CAU">
</div>
</body>
CodePudding user response:
Can you please add the script code in head section. See my demo here.
<head>
<script>
function callfunc(item){
alert(item)
}
</script>
</head>
<body>
<img onclick="callfunc(1)" src="./dummy.png" />
<img onclick="callfunc(2)" src="./dummy.png" />
</body>
</html>```
CodePudding user response:
just change the order, in onclick you are executing a function that is not defined yet otherwise
<script>
function picture(picnumber){
alert(picnumber);
}
</script>
<img onclick="picture(1)" src="asd.jpg">
<img onclick="picture(2)" src="sdf.jpg">