Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

joecool85

macrumors 65816
Original poster
Mar 9, 2005
1,355
4
Maine
How would I go about having an image on my site that when clicked refreshes? I'd like to use javascript if possible.
 

rob finch

macrumors member
Mar 24, 2006
93
0
England
FredClausen said:
I think if you look at code examples for onmouseover events for swapping images and change onmouseover to onclick, it will work for you.

You can find an exact example of that here. Change the event for the image to onClick, get it to call a function to refresh the source for the image to the same file it is initially set to. Should work.
 

joecool85

macrumors 65816
Original poster
Mar 9, 2005
1,355
4
Maine
Ok...well, I tried this:

<html>

<head>
<title>Image reload page, thanks javascript!</title>

<script type="text/javascript" language="JavaScript">
function reloadImage()
{
img = document.getElementById('theimage');
img.src = '2.jpg?' + Math.random();
}
</script>

</head>
<body>

<img src="radar.jpg"
name="theimage" alt="radar image"
onclick="reloadImage();"
/>

</body>
</html>

But it won't load 2.jpg when you click it...anyone know why?
 

rob finch

macrumors member
Mar 24, 2006
93
0
England
joecool85 said:
function reloadImage()
{
img = document.getElementById('theimage');
img.src = '2.jpg?' + Math.random();
}

What are you trying to achieve with the random number? You will get returned "2.jpg?0.678864716868319" or similar for the source of the image, so it clearly won't load.

To see the value that you are getting back, pop up a dialogue box using the following in the function.

Code:
alert ("2.jpg?"+Math.random())
 

joecool85

macrumors 65816
Original poster
Mar 9, 2005
1,355
4
Maine
I read that what that does is make sure the browsers thinks its loading a different picture (its made to be a refresh, I just have it set to two different pics for testing purposes).
 

rob finch

macrumors member
Mar 24, 2006
93
0
England
It won't load an image if you give it's source as something that doesn't exist as a path, i.e. "2.jpg?+random number".

Try just just using img.src = "2.jpg" in the function, it should cause it to load that picture. If that works, try restating the source as img src="radar.jpg", edit the picture and save it, then click the image to call the function.
 

cciapocka

macrumors newbie
Mar 3, 2011
1
0
Maybe it's too late :)

The mistake is in name="theimage", in javascript you're looking for 'id'. Change the attribute 'name' to 'id' and it will be well.
 

joecool85

macrumors 65816
Original poster
Mar 9, 2005
1,355
4
Maine
Wow...talk about dredging up old posts.

Thanks for the help. I've long ago figured it out though. :cool:
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.