Reloading IMG with click() in jQuery

Trying to do a simple search and image load page for my website. It works great on the first click, but the image doesn’t refresh when I enter a new search query.



<html>
<head>

<title>Animal Testing</title>

<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>

<style type="text/css" media="screen">
  BODY { margin: 10px; padding: 0; font: 1em "Trebuchet MS", verdana, arial, sans-serif; font-size: 100%; }
  H1 { margin-bottom: 2px; }

  DIV#loader {
      border: 1px solid #ccc;
      width: 700px;
      height: 580px;
      overflow: hidden;
  }

  DIV#loader.loading {
      background: url(spinner.gif) no-repeat center center;
  }
</style>

<script type="text/javascript">
  $(document).ready(function() {
  $('#preloader').show();
  $('#loader').hide();

  $('#searchButton').click(function() {
    $('#loader').show();
    $('#preloader').hide();

    var $currentAnimal = null;
    $currentAnimal = $("#animal").val();
    //$currentAnimal.replace('/','');

    var img = new Image();

    $(img).load(function () {
      //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
      $(this).hide();
      $('#loader').removeClass('loading').append(this);
      $(this).fadeIn();
    }).error(function () {
      // notify the user that the image could not be loaded
    }).attr('src', 'http://www.website.com/images/=' + $currentAnimal + '');

  });

});
</script>

</head>

<body>

<input type="text" id="animal" name="animal" value="Enter an animal">
<input type="button" id="searchButton" value="Enter">

<div id="preloader">
This is shown before the click, and will be hidden when the box is clicked
</div>

<div id="loader" class="loading"></div>

</body>

</html>

I thought breaking up and resigning the loading class would work, but it doesn’t.


var img = new Image();

    if (! $('#loader').hasClass('loading')) {
      $img = null;
      $('#loader').addClass('loading');
    }
...

When I set up a test using your code, the problem seemed to be that when you entered a new search term, the new image would be loaded alongside the first image. Is that correct?

If so, the fix is pretty straightforward: Before creating and adding the new image, you first need to remove any images that may be there already.

It might not look so sexy, but a really quick way to do it is with jQuery’s .remove method:


$('#searchButton').click(function() {
    $('#loader').show();
    $('#preloader').hide();
    $('#loader img').remove(); // <-- add this line here

    // ...