SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot auth1's Avatar
    Join Date
    Nov 2004
    Melbourne, Australia
    0 Post(s)
    0 Thread(s)

    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.

    <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;
    <script type="text/javascript">
      $(document).ready(function() {
      $('#searchButton').click(function() {
        var $currentAnimal = null; 
        $currentAnimal = $("#animal").val(); 
        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
        }).error(function () {
          // notify the user that the image could not be loaded
        }).attr('src', '' + $currentAnimal + '');  
    <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 id="loader" class="loading"></div>
    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;

  2. #2
    SitePoint Enthusiast aufshebung's Avatar
    Join Date
    May 2012
    Santa Fe, NM
    0 Post(s)
    0 Thread(s)
    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:

    Code javascript:
    $('#searchButton').click(function() {
        $('#loader img').remove(); // <-- add this line here
        // ...


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts