user1387147
user1387147

Reputation: 955

javascript on click event is not working fine on img tag

I am trying to open a link on image click using follwoing code

 <img src="AllScripts/SliderImages/images/1Main.png" alt="" title="" onclick="openSliderImage(id);"  onmouseover="this.style.cursor='hand'"  width="800px" height="300px" id="http://www.google.com" />

It is working fine but when generating image using c# write code using response.write code it doesn't work and goes on the follwoing link

http://localhost:1234/AllScripts/SliderImages/images/1Main.png

Follwoing code is used to write html

 <% {

                               Response.Write(SlidingImages);
                       }

                    %>

I know it pick the image src rather then image id on image click but why? This is the javascript function

 function openSliderImage(id) {
            alert(id);
            window.open(id, '_blank');
        }

Upvotes: 0

Views: 507

Answers (2)

nunespascal
nunespascal

Reputation: 17724

Using ids like that to open links seem like a hack. I would just output the url to like link it has to open as a parameter to the function directly.

<img id="googleImg" onclick="openSliderImage('http://www.google.com');" src="AllScripts/SliderImages/images/1Main.png" alt="" title=""   onmouseover="this.style.cursor='hand'"  width="800px" height="300px" />

Your code doesn't run cause it will look for a javascript variable by the name 'id'.

Upvotes: 1

voigtan
voigtan

Reputation: 9031

change id (because you are refering to a javascript variable named id, you want to target the image id then use this.id

<img src="AllScripts/SliderImages/images/1Main.png" alt="" title="" onclick="openSliderImage(this.id);"  onmouseover="this.style.cursor='hand'"  width="800px" height="300px" id="http://www.google.com" />

I would also say you could remove onmouseover and set it with CSS (if with IE7+) img:hover (or set a cssClass so not all your images will be targeted).

Upvotes: 1

Related Questions