Monday, 17 April 2017

How to use client side javascript variables as array index?

So I'm trying to teach myself to make a website. I'm using node and expressJS server side to send the template to the client like this.

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {

    var cityData = require("../public/cityData/paris.json");

    res.render('index', {
        cityData : cityData 
     });
});

module.exports = router;

In this case I'm just passing a JSON file with information about the city of Paris that I want to display to the client. It has an array of image URLs that I can use for pictures. My issue is that I only want to show one image at a time and change the image to the next one when a key is pressed (or a button if necessary, but preference for key).

My issue comes on the client side, I can get the JSON object and generate the page based on it if I use a value eg [0] in the place of the "index" variable, but if I have it setup as shown, index is "undefined". So my question is, how does one make a variable that will exist clientside and allow me to rerender the page with a new picture, is that even possible? I've been reading stack overflow for hours and nothing seems to be what I want.

Thanks.

HTML code --->

<% include templates/head.ejs %>

<script "text/javascript" >
    var index = 0;
</script>

<body>
    <!-- This imports the naviagtion template I made -->
    <% include templates/navigation.ejs %>
    <div id="wrapper">
        <% include templates/sidebar.ejs %>
        <!-- Page Content -->
        <div id = "page-content-wrapper">
            <div class="container-fluid">
                <!-- This imports an image -->
                <div class = "row">
                    <div class = "text-center">
                         <img id = "imgArea" src = <%- cityData.imageUrl[index] %> class = "img-rounded col-xs-12 col-md-6" width = "device-width">
                    </div>
                </div>   
            </div>
        </div>
    </div>

    <!-- Menu Toggle Script -->
    <script>
        $("#menu-toggle").click( function(e) {
            e.preventDefault();
            $("#wrapper").toggleClass("menuDisplayed");
        });
        $(document).keydown(function(e){
            index ++;
            document.getElementById("imgArea").innerHTML = cityData.imageURL[index];
        });
    </script>
</body>



via laminatedlama

No comments:

Post a Comment