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:
HTML:
<body>
    <div id="wrap">
        <div class="firstColumn">
            <p>PHOTOGRAPHY</p>
            <div class="firstColumnSub">
                <p class="photo">SOME TITLE</p>
            </div>
        </div>
        <div class="back">
            <p><a href="index.html">BACK</a></p>
        </div>
        <div id="container">
            <div id="controllers">
                <div class="buttons" id="previous">
                    <p onclick="change(-1);">PREVIOUS</p>
                </div>
                <div class="buttons" id="next">
                    <p onclick="change(1);">NEXT</p>
                </div>
            </div>
            <div><img height="100%" id="front" src="Image1.jpg"></div>
            <div>
                <p id="footer">Footer</p>
            </div>
        </div>
    </div>
</body>
Just a few divs with the image in the center and a previous and a next clickable tags. This is what it loos like:
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:
JavaScript:
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:
etc... but instead I get all sort of random displays:
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.





 
     
     
    