Paul Paul - 10 months ago 71
HTML Question

Basic Image Viewer with javaScript

I am new with JavaScript and I am trying to learn by coding. I want to make a basic image viewer with a "next" and a "previous" that you can click to move forwards and back through a gallery of ten pictures. So I have my html, my css and my javaScript files and 10 random pictures to try it out.
The files are pretty straight forward:


<div id="wrap">
<div class="firstColumn">
<div class="firstColumnSub">
<p class="photo">SOME TITLE</p>
<div class="back">
<p><a href="index.html">BACK</a></p>
<div id="container">
<div id="controllers">
<div class="buttons" id="previous">
<p onclick="change(-1);">PREVIOUS</p>
<div class="buttons" id="next">
<p onclick="change(1);">NEXT</p>
<div><img height="100%" id="front" src="Image1.jpg"></div>
<p id="footer">Footer</p>

Just a few divs with the image in the center and a previous and a next clickable tags. This is what it loos like:

enter image description here

The JavaScript file contains a function that loads the different pitures and -and this is my problem- centers them in the middle of the page by grabbing their width and updating the css:


window.onload = function setUp() {
var b = document.getElementById("front").width;
document.getElementById("container").style.width = b + "px"

var imageCount = 1;

function change(x) {
imageCount = imageCount + x;
var image = document.getElementById('front');
var str1 = "Image";
var str2 = imageCount;
var str3 = ".jpg"
var sum = str1.concat(str2, str3);
image.src = sum;
var a = document.getElementById("front").width;
document.getElementById("container").style.width = a + "px"

I an not posting the css unless required, but you get the idea.

As you press "next" or "previous", you are supposed to get this result:

enter image description here

enter image description here

etc... but instead I get all sort of random displays:

enter image description here

enter image description here

And here is the thing that is puzzling me: if you keep clicking "back" and "next", the same pictures appear OK the second time round, so it is working but not immediately. Any help appreciated!
Thanks, P.


This is most likely a CSS positioning issue. The following CSS may do the job for you. If you need further help, then I suggest that you reconsider posting your CSS to get help.

 #container #front
    position: relative;
    /* width: 0px;  */ /* set via JS for each element in this use case */
    left: 0;
    right: 0;
    margin: 0 auto;

Here is a popular Q & A on this subject which contains a lot of resources.