Utilizing an array to cycle through various images

Initially, I'm facing an issue with morscreens[i] not displaying the desired image from the array. When left as it is, it ends up showing a [<] button followed by "morscreens[i]" and then a [>] button. However, enclosing morscreens[i] in quotes causes an error stating that morshots() is not defined.

Furthermore, if I aim to cycle through the buttons, would it be advisable to utilize subroutines like morPrev() and morNext()? My concern revolves around potentially encountering scope-related challenges when trying to return the desired value and correctly placing it in the required locations. Simply incrementing and decrementing i using i++ and i-- may not suffice for achieving the intended functionality, even with the presence of 2 conditional statements.

var mordorscreens = new Array();
mordorscreens[0] = '<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\">';
mordorscreens[1] = '<img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns1\">';
mordorscreens[2] = '<img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns1\">';

function morshots()
{
    var i = 0;
    var mordor = document.getElementById("ss1");
    mordor.innerHTML = '<button onClick="morPrev();"> < </button> ' + mordorscreens[i] + ' <button onClick="morNext();"> > </button> ';

    if (i<0) {i=2};
    if (i>2) {i=0};
}

Answer №1

This particular line

'<button onClick="morPrev();"> < </button>    
                mordorscreens[i]    <button onClick="morNext();"> > </button> ';

was intended to appear like this

'<button onClick="morPrev();"> &lt; </button>' 
             + mordorscreens[i] + '<button onClick="morNext();"> &gt; </button>';

I believe it is not advisable to expose the variable i for iterating through the images. It would be better to set the event handlers in Javascript rather than in HTML.

You can test out this code

HTML

<div id="ss1">
   <button id="previous"> &lt; </button>
   <span id="imageSpan"></span>
   <button id="next"> &gt; </button>
</div>

Javascript

var mordorscreens = [];
mordorscreens[0] = '<img src="http://i.imgur.com/83HCt.png" alt="scrns1">';
mordorscreens[1] = '<img src="http://i.imgur.com/5mWIy.png" alt="scrns1">';
mordorscreens[2] = '<img src="http://i.imgur.com/pPafl.png" alt="scrns1">';

function morshots() {
    var i = 0;
    var elem = document.getElementById('imageSpan');
    elem.innerHTML = mordorscreens[i];
    // Data Attribute that holds the initial 
    // image number
    elem.setAttribute('data-number', i);
}
// Call The function
morshots();

// Assign Event handlers
var buttons = document.getElementsByTagName('button');

for (var j = 0; j < buttons.length; j++) {
    // Add Click events to the button
    buttons[j].addEventListener('click', clickHandler);
}

function clickHandler() {
    var elem = document.getElementById('imageSpan');
    // Store the current Image Number in a HTML5 data-attribute
    var currImage = parseInt(elem.getAttribute('data-number'), 10);
    if (this.id === 'previous') {
        currImage--;
        currImage = currImage < 0 ? 2 : currImage;
    }
    else if (this.id === 'next') {
        currImage++;
        currImage = currImage > 2 ? 0 : currImage;
    }
    // Set the current Image Number 
    elem.setAttribute('data-number', currImage);
    elem.innerHTML = mordorscreens[currImage];
}

Explore JSBin Demo

Answer №2

Here is a simple string without any variables:

mordor.innerHTML = '<button onClick="morPrev();"> < </button>    mordorscreens[i]    <button onClick="morNext();"> > </button> ';

To extract the value, you can do it like this:

mordor.innerHTML = '<button onClick="morPrev();"> < </button>'  +  mordorscreens[i]  +  '<button onClick="morNext();"> > </button> ';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display several components in a particular location within a parent component using react-native?

I am struggling to position multiple components within a parent component at a specific location determined by some calculations. The calculations for the vertical position seem accurate, but the components are not appearing where they should be. I have ex ...

Having trouble with your JSONP callback not being received?

When attempting to make a JSONP request to yellowapi (Yellow Pages) and specifying a callback, I encountered an "invalid label" error. Below is the code I currently have: $.ajax({ dataType: 'jsonp', cache : false, url: "http://api.sandbox.yell ...

Can anyone provide a method for obtaining a date that is x days earlier through date arithmetic?

Is there a method to obtain the date from 63 days ago with only day, month, and year information needed, excluding hours, minutes, and seconds? I am aware that one can calculate Date object - Date object, but I am curious if it is feasible to derive a dat ...

Ways to eliminate the occurrence of 'undefined' in Object.keys while using forEach loop

Hey there! I'm currently working with Node.js and running into an issue with using forEach on Object.keys. In the code snippet below, when I try to execute it, I encounter a problem where the first value in the output is undefined. For instance, let&a ...

Discover how to capture a clicked word within the Ionic Framework

I've been working on an app using the Ionic Framework. I am trying to figure out how to detect when a word is pressed in my application. One solution I tried involved splitting the string into words and generating a span with a click event for each on ...

Calculate the total width of all images

I'm on a mission to calculate the total width of all images. Despite my attempts to store image widths in an array for easy summing, I seem to be facing some challenges. It feels like there's a straightforward solution waiting to be discovered - ...

Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval. var Arrow = (function () { function Arrow() { this.intVariable = 1; this.itemId = -1; this.interval = 25; } Arrow.p ...

Issue with jQuery: Function not triggered by value selection in dynamically created select boxes

I am in need of some assistance with my code that dynamically generates select drop down menus. I want each menu to trigger a different function when an option is selected using the "onchange" event, but I am struggling to implement this feature. Any hel ...

Discovering the worth of specific selections in a dropdown menu

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <select name="states" id="states"> <option value="100">Hawaii</option> <option value="107">Texa ...

"The `Head.js` method called `.js()` allows for dynamic

Recently, I came across some code that was passed down to me from work, and it involves making an api call using head.js: head.js( { 'application' : 'someurl.com/foo.js' }); I'm curious if this actually registers the javascript a ...

What is the best way to display a collection of images in an HTML page?

I have a list of strings containing images. How can I display these images on a webpage using Angular? images: [ "https://images.oyoroomscdn.com/uploads/hotel_image/1097/340ea5ee01acc37f.jpg", "https://images.oyoroomscdn.com/uploads/hotel_image/1097 ...

Encountering a "Start script missing" error while trying to execute npm start, the problem remains even after attempting

Help, I keep encountering this issue npm ERR! missing script: start whenever I attempt to execute 'npm start' for my latest React project. I've tried searching for a solution and came across some individuals who were able to resolve it by u ...

Learn to leverage JavaScript in Node-RED to dynamically display messages based on selected dropdown options

After reviewing this Node-red flow: https://i.stack.imgur.com/y4aDM.png I am struggling with the implementation in my function. There are 3 options in each dropdown, one for meat type and the other for doneness. Once I select a combination from the drop ...

How do I overwrite this calculation using JQuery?

I have a website: link There are two pages on my site that have the same div elements... I want one page to perform a certain calculation on the divs, and another page to perform a different calculation... New JavaScript Code: jQuery(document).ready(fu ...

At what point should the term "function" be included in a ReactJS component?

As a beginner in ReactJS, I have been working through some tutorials and noticed that some code examples use the keyword function while others do not. This got me wondering what the difference is and when I should use each one. Render Example with functi ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

What is the cause behind the failure of this regular expression in JavaScript?

I have been struggling to make this code display "matched!" for the specific string. I've tried various methods but nothing seems to be working. Here's the HTML part: <div id="ssn">123-45-6789</div> And here's the JavaScript p ...

Leveraging real-time geographical location data for a weather widget with OpenWeatherAPI integration

My goal is to incorporate the current geolocation feature into a weather widget that I am developing. At the moment, I can only show data from cities based on an external source. My coding knowledge is quite limited. I am not a professional in this field, ...

The Ajax success callback is failing to update the background-image property after receiving a successful JSON response

I am struggling with setting a background image in wordpress despite receiving a successful ajax response. The image url is being returned successfully in the json response, but I can't seem to set it as a background image. Here is the ajax function ...

Tips for fixing the Runtime.UnhandledPromiseRejection error when deploying your next.js project on Vercel and Netlify

Encountering an error during deployment on Vercel or Netlify. The same error persists on both platforms. Any suggestions on resolving this issue would be greatly appreciated. Snippet of the Database code: import mongoose from 'mongoose'; const ...