Switch up the image source with Javascript in a random sequence

Looking to create a script that randomly changes the image source of an element with one specified in an array. However, the variable "target" keeps returning undefined. Can you help?

HTML

<ul>
    <li><img src="http://www.placehold.it/20x20" /></li>
    <li><img src="http://www.placehold.it/20x20" /></li>
    <li><img src="http://www.placehold.it/20x20" /></li>
</ul>

JAVASCRIPT

let slideImages = [
   'http://www.placehold.it/100',
   'http://www.placehold.it/101',
   'http://www.placehold.it/103',
   'http://www.placehold.it/105',
   'http://www.placehold.it/99',
   'http://www.placehold.it/98',
   'http://www.placehold.it/96',
   'http://www.placehold.it/107'
]

let totalImages = slideImages.length;
let randomNo = Math.random() * totalImages;
let imageURL = Math.floor(randomNo)
let img = slideImages[imageURL];


let options = document.querySelectorAll('li');
let random = Math.random() * options.length;

let target = options[random];

var fadeImagesFn = (target, img) => {
   console.log(img, target);
}

fadeImagesFn(img);

Answer №1

The issue can be found within the following two lines:

let randomNumber = Math.random() * choices.length;
let chosenOption = choices[randomNumber];

Math.random() generates a decimal number between 0 and 1. When this is multiplied by the length of choices, it results in decimal values between 0 and the choices.length, not necessarily whole numbers.

For instance, if Math.random produces 0.7, and there are 7 choices available, randomNumber will equal 4.9.

Therefore, attempting to access choices with a non-integer value will lead to undefined being returned. To rectify this, the values must be converted back to whole numbers, possibly by utilizing Math.floor.

Answer №2

When accessing a float index of an array, you may encounter undefined values. To prevent this, utilize Math.floor before indexing.

let items = document.querySelectorAll('li');
let num = Math.random() * items.length; // <- float
let selection = items[num]; // <- array-like [ float ] = undefined

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

Issues with javascript and php carousel functionality not performing correctly

I am currently in the process of creating a slideshow/carousel for a website. Recently, I implemented a PHP for-loop to iterate through a folder of images, allowing me to use the slideshow with an unspecified number of images. However, after making this ch ...

Looking for assistance with REGEXP to handle a 404 path rendering issue

I am attempting to utilize REGEXP in order to display a 404 page within a react app based on the path, but I am struggling to make it work. This is the specific REGEXP pattern I am trying to achieve: The entire path should not be '/' and should ...

Unlock the secrets of programming with the must-have guide to mastering variables

As a newcomer to the world of programming, I may be jumping ahead by asking this question too quickly. While reading a book, I came across something that confused me. Why is it necessary to create a variable for the password box element? Wouldn't the ...

Is there a way to retrieve the left offset of a floating element even when it is positioned outside the viewport?

My current situation involves creating several panels that are stacked side by side within a main container. Each panel takes up 100% of the viewport width and height. I want to be able to horizontally scroll to each panel when clicking on their respective ...

"Enhance Your Website with Slider Swipe Effects using CSS3 and

After scouring the internet for various types of sliders, including swipe sliders, I am interested in creating a responsive swipe slider specifically for mobile phones. This would be a full page swipe slider where users can swipe left and right seamlessly. ...

Developing a collection of reusable components in a Javascript bundle for enhanced efficiency

I currently have a backend rendered page (using Django) that I want to enhance by incorporating components from PrimeVue and a markdown editor wrapped as a Vue component. Previously, we utilized some simple animations with jQuery which we included directly ...

Tips for incorporating JavaScript into your Selenium WebDriver workflow using Java

Looking to integrate JavaScript with WebDriver (Selenium 2) using Java. After following a guide listed on the Getting Started page, I found an initial instruction to run: $ ./go webdriverjs Curious about the specific folder/location where the above ...

Converting line breaks into a visible string format within Angular

After thorough research, all I've come across are solutions that demonstrate how to display the newline character as a new line. I specifically aim to exhibit the "\n" as a string within an Angular view. It appears that Angular disrega ...

What are some ways I can troubleshoot my contact form?

As someone new to web design, I recently completed my very first site using a combination of HTML, CSS, and a touch of JavaScript. I managed to create a small contact form within the site, but now I'm wondering if there's a way to make it functio ...

What is the best way to generate a complete PDF of a webpage using pdfmake?

I'm currently developing a web application and facing the task of converting an HTML page, which contains multiple tables and datatables, to a PDF format. To achieve this, I've chosen to utilize the library pdfmake. Below is the script that I ha ...

Creating route paths within a single .js file

I'm a beginner when it comes to Node/Express, and I have a question about my app structure. Here is a simplified version of how my app is set up: /app /routes filter.js index.js app.js In my app.js file, I have defined my routes like th ...

Newbie in PHP: Techniques for transferring PHP variables between different sections of PHP code

In my project, I have a file named index.php which is responsible for uploading files to the server and setting PHP variables such as $target_folder_and_file_name. This index.php file also includes the following line (originally it was in an index.html fi ...

Having trouble accessing a DOM element within a Vue component while using vanilla JavaScript

I am attempting to dynamically update data from a Vue component using jQuery in a Webpack project. Below is the code snippet: <template> <div id="container"> <slot>show string!!</slot> <div id="s_container"&g ...

Every time I attempt to execute this piece of code in "node.js", an error pops up

const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const https = require('https'); const app = express(); app.use(express.static('public')); ...

Error: Unable to execute this.context.router.push due to it not being a function

I recently encountered an issue where the browser console displayed the same message as the post title. The problem occurred when trying to navigate to a profile page after clicking a dropdown button. contextTypes: { router: React.PropTypes.func }, _h ...

Include buttons in the HTML template once JSON data has been received

I am working on a feature to dynamically add buttons to the DOM using JSON data fetched from an API when users visit the site. Although I have successfully implemented the function to retrieve the data, I am facing challenges in adding these buttons dynami ...

Tips for changing ES lint rules in a specific file within a React application

Currently, I am incorporating some older code into my React application. Webpack is generating numerous errors related to "no-restricted-globals" and "no-undef," which is preventing successful compilation. I am interested in finding a way to bypass this f ...

Eliminate the flickering effect on the dropdown menu

Is there a way to eliminate the annoying 'flicker' effect on my menu? Whenever I click on 'Dropdown 1', I notice that Test 1 and Test 2 flicker. My assumption is that this is due to my use of the !important declaration. Any suggestion ...

Guide on using PHP to remove the trash icon glyphicon

I am currently creating a data table that includes various actions, one of which is the option to delete a row from both the table and the database. My challenge lies in figuring out how to successfully delete a particular row by simply clicking on the Tr ...

retrieve trackpoint information using OpenLayers

When displaying a map with a GPX track using OpenLayers 5.3, I noticed that the trackpoints default to a MultiLineString geometry type. The example provided in the GPX-example actually has a larger file size because all of the <trkpt> tags are duplic ...