views:

292

answers:

1

Dear web developers, I want to create a captcha in my website. I will try to describe how I want to do that. See the code below please:

<img src=”captcha_img.png”>   <img src=”reload.png”>  <a href=”..”>Reload Captcha Image</>

What I want to do is, to click on “Reload Captcha Image” link and with JavaScript change the content of the first img tag to a new captcha image, and simultaneously to change reload.png to reload.gif which is and animation that I want to last as much as the new captcha image is being processed. And I want to change back the reload.gif animation to the reload.png static image, right the same time when the new captcha image has been load image. The problem is that the captcha image is being generated by GD library of PHP, and I don’t know how much time that will take to create a new image. Please help me to be able to synchronize. May be there is a good approach for doing this kind of things…

Thanks!

+1  A: 

You can use the onload event on the image, to know exactly when your new captcha image has been loaded on the browser, I added IDs to your markup:

<img id="captcha" src="captcha_img.png">
<a id="reloadLink" href="..">
  <img id="reloadImg" src="reload.png"> Reload Captcha Image
</a>

Then in your code, you connect the event handlers:

// Connect event handlers
window.onload = function () {
  // get the DOM elements
  var captcha = document.getElementById('captcha'),
      reloadImg = document.getElementById('reloadImg'),
      reloadLink = document.getElementById('reloadLink');

  // reload the captcha image when the link is clicked
  reloadLink.onclick = function () {
    var captchaURL = "captcha.php"; // change this with your script url

    captcha.src = captchaURL + "?nocache=" + (+new Date()); // cache breaker
    reloadImg.src = "reload.gif"; // set "animated" reload image
    return false; // prevent link navigation
  };

  captcha.onload = function () { // when the captcha loaded, restore reload image
    reloadImg.src = "reload.png"; // "static" reload image
  };
};
CMS
Thank you so much!!! That worked.
Narek