4

I have the code below and what I need to do is load the image from the href into a div via ajax... Any help appreciated. I believe that load() can't load images like this?

    <ul id="list">
    <li class="list-item-1"><a href="images/image1.jpg">Image 1</a></li>
    <li class="list-item-2"><a href="images/image2.jpg">Image 2</a></li>
    <li class="list-item-3"><a href="images/image3.jpg">Image 3</a></li>
    <li class="list-item-4"><a href="images/image4.jpg">Image 4</a></li>
    </ul>
<div id="image-holder"></div>

Many thanks, C

  • 1
    You don't really load images via ajax. Each image will make it's own request for the image via the src attribute. If you change the image src via JavaScript, it will load the new image. DutrowLLC is on the right track. – Gregg Dec 02 '10 at 17:39

4 Answers4

13

You have to also remove the currently appended image. Here it is with a click event and Image instead of appending markup.

$('#list li a').click(function () {
    var url = $(this).attr('href'),
    image = new Image();
    image.src = url;
    image.onload = function () {
        $('#image-holder').empty().append(image);
    };
    image.onerror = function () {
        $('#image-holder').empty().html('That image is not available.');
    }

    $('#image-holder').empty().html('Loading...');

    return false;
});
mqsoh
  • 3,180
  • 2
  • 24
  • 26
  • Thanks eveyone. The reason I mentioned ajax/load() is because it detects when an image has loaded, if there was an error etc. What I would like to do is show a preloader until the image has loaded. Then remove preloader and fade out original image to show new one. Possible? –  Dec 03 '10 at 09:39
  • I edited the original post with the loading and error message. The Image DOM object has error and load events: http://www.w3schools.com/jsref/dom_obj_image.asp – mqsoh Dec 03 '10 at 14:45
  • Very nice! has the advantage over forcing an ajax load that if you trigger it again to the same url it doesn't reload (my use case is loading a preview image from a web service which draws the image based on query parameters so this is a big plus) – Adam Mar 05 '14 at 16:33
3

This would be the first thing I would try, I'm also a bit of a beginner as well though:

var image = $('<img></img>');
image.attr('src', 'images/image1.jpg');
$('#image-holder').append(image);
Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258
1

Okay. Messy but it works perfectly. A few tweak like adding the images as background images. Here it is and I hope it helps someone else! Thanks so much everyone.

<script type="text/javascript">
$(function(){
    var list = $("#list");
    var li = list.children();
    var lengthMinusOne = li.length - 1;
    var index = 0;
    var num = $("#list li").length;
    var prevLi = $(li[0]).css("background-color", "gray");

    $("#next").click(function(){
       index++;
       if (index > lengthMinusOne) index = 0;
       prevLi.css("background-color","white");
       prevLi = $(li[index]).css("background-color", "gray");

       //Trigger a href click
       $(prevLi).children('a').trigger('click');

       //Display class in console
       var myClass = $(prevLi).attr("class");
       console.log(myClass);
    });
    $("#prev").click(function(){
       index--;
       if (index < 0) index = lengthMinusOne;
       prevLi.css("background-color","white");
       prevLi = $(li[index]).css("background-color", "gray");

       //Trigger a href click
       $(prevLi).children('a').trigger('click');

       //Display class in consol
       var myClass = $(prevLi).attr("class");
       console.log(myClass);
    });


    //Loader
    loader = $('#loader');
    loader.hide();
    var firstImg = $('<img />');
    $(firstImg).attr('src',$('#list li a').attr('href'));
    $('#image-holder').append(firstImg);

    //get image and load into div
    $('#list li a').click(function(event) {                        
        //Add class to image within holder
        oldImg = $('#image-holder img').addClass('old');
        newImg = $('<img />');

        $(newImg).attr('src',$(this).attr('href'));
        //remove old image and show loader
        $(oldImg).fadeOut().remove();
        loader.show();

        $(newImg).bind({
            load: function() {          
                //console.log("Image loaded");
                //Hide loader before fading in image
                loader.hide();
                $('#image-holder').append(newImg).hide().fadeIn(1300);
            },
            error: function() {
                //console.log("Error thrown, image didn't load, probably a 404.");
            }
        });

        event.preventDefault();
    });


})
</script>
  • If you can think of any tidy ups that would be great, just to get even quicker page load. –  Dec 03 '10 at 11:12
0

If you want to change image dynamically use dom What you need to do is change the img src attribute

say img_div is your parent element then

var im = document.createElement('img');
im.src = 'image_path1';
img_div.appendChild(im);

on some event if you want to change this image

im.src = 'image_path2'
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
gyogesh
  • 1
  • 1