views:

50

answers:

5

Hi

<a href="#"><img src="logo.gif" onClick="alert('hi')"/></a>

In the above code, I am appending a javascript onclick method to the image tag. When I click the image once and I press back, it should go back to the page it came from. Instead its staying on the same page. Is there any way I can avoid that? (probably set something else instead of href="#"). The reason I set href="#" is to make my cursor turn into hand, other than that it has no use.

This is occuring in Firefox. In IE it works fine.

Please help. Thanks.

+1  A: 
<a href="#"><img src="http://www.google.com/intl/en_ALL/images/logo.gif" onClick="alert('hi'); return false;"/></a>

you need add return false; to your onclick events if you don't want to load the link.

Ross
that was quick! thank you very much !
Bragboy
you're welcome.
Ross
Not exactly related to this issue, but its better to have the click event on `a` than on `img`
Teja Kantamneni
@Teja, yes I would say on `a`
Ross
+1  A: 
<a href="#">
<img src="http://www.google.com/intl/en_ALL/images/logo.gif" 
    onClick="alert('hi'); return false;"/>
</a>

return false prevents the default action from occurring (in this case navigating to "#"), and then navigating back will return you to the previous page, instead of to the current page without "#".

Andy
+3  A: 

The reason I set href="#" is to make my cursor turn into hand, other than that it has no use.

You can remove the <a href="#"> and add the cursor: pointer style to the image:

<img src="logo.gif" style="cursor: pointer;" />

... to turn the cursor into a hand.

On the other hand, it is probably better to follow the guidelines for progressive enhancement, as David suggested in another answer.

Daniel Vassallo
more info here on @Daniel's comment: http://stackoverflow.com/questions/2433185/help-needed-in-javascript-image-href/2433193#2433193
Ross
+1  A: 

Follow the pragmatic guidelines for progressive enhancement. In particular: Build on things that work.

David Dorward
+1  A: 

Use this instead: <img src="http://www.google.com/intl/en_ALL/images/logo.gif" onClick="alert('hi')" style="cursor:pointer"/>

AlfonsoML