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!

1
  • Set an id of "img" on the target element? Commented Aug 19, 2013 at 17:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 replaceWith will replace the current jQuery object with the contents provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.