0

I'm trying to display images that are sent from the controller to the view. On the view page, I want to display the image, and I have 2 buttons "forth" and "back" to iterate over these images.

//controller:
var images= [path1 , path2, path3];
var currentImageIndex=0;
function goToNextImage() { // is called when forth button is clicked
   if (currentImageIndex +1 < images.length) {
      currentImageIndex ++;
       imageDisplay= ImageDisplay(images, currentImageIndex);
   }
}

$(document).ready(function() {
   imageDisplay= ImageDisplay(images, currentImageIndex);
   $('body').append(imageDisplay);
});

// the body of my index file is empty. I append everything to the body from the javascript file

// view (javascript file)

function ImageDisplay(images,currentImageIndex) {
var me = $('<div/>');
   drawImage();


 function drawImage( ) {
      var windowWidth= $(window).width();
      var windowHeight=$(window).height();
      var imageSrc= images[currentImageIndex];
      var image = $ ('<img id="img" src="'+imageSrc+'" alt="NO IMAGE" width="'+windowWidth/2+ '" height= "'+windowHeight/2+'" class="image_display"/>');
      console.log("image source= "+imageSrc);

    me.append(image);
}
return me ;
}

The problem is that the displayed image is always the same (Although the image source changes). I read here Change image source with javascript that I should use document.getElementById("img").src to set the new source. But as I don't have any img id in my html file, I got this error "cannot set property src of null".

Thank you for help!

Community
  • 1
  • 1
user1499220
  • 419
  • 4
  • 12
  • 23

1 Answers1

1

var me = $('<div/>'); is basically (read: actually) creating a new node. You're adding content to that node, but you're never actually adding it to the DOM. You probably mean something like this:

var newImage = ImageDisplay(images, currentImageIndex);
imageDisplay.replaceWith(newImage)
imageDisplay = newImage;

That said, I have no idea if you've ever assigned imageDisplay a value inside of the DOM. If not, then you may need to initialize that value.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • Thank you for your answer. I did add imageDisplay to the DOM (otherwise I would not be able to see any image). See my edited question. In your answer , you do imageDisplay.replaceWith(newImage), I'm a bit confused, what's imageDisplay for you? – user1499220 Aug 19 '13 at 18:54
  • @user1499220 `replaceWith` will replace the current jQuery object with the contents provided. – cwallenpoole Aug 19 '13 at 19:00