What is preventing the random images from appearing on my browser?

Having some trouble loading random images on a page using basic JavaScript code. Following homework instructions, but the images are not showing up in the web browser. Any assistance would be greatly appreciated. Here is the code:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- 
   New Perspectives on HTML and XHTML 5th Edition
   Tutorial 10
   Review Assignment

   Monroe Public Library
   Author: Collin Klopstein
   Date: November 13, 2013   

   Filename:         mpl2.htm
   Supporting files: mpl2.jpg, mplstyles.css, random.js, 0.jpg - 9.jpg
-->

   <title>Monroe Public Library</title>
   <link href="mplstyles.css" rel="stylesheet" type="text/css" />

   <script type="text/javascript">
        function showImg() {
            /*
                the showImg() function displays a random image from the 0.jpg through 9.jpg files.
                The random image is designed to thwart hackers attempting to enter the library records database by requiring visual confirmation.
            */

            var imgNumber = randomInteger(9);//return a random number from 0 to 9
            document.write("<img src='imgNumber.jpg' alt='' />");
        }

        function randomInteger(size) {
            return Math.floor((size+1)*Math.random());
        }
   </script>
</head>

<body>
<div id="pageContent">
   <div id="head">
      <img src="mpl.jpg" alt="Monroe Public Library" />
   </div>

   <div id="links">
    ...
               ...
                  ...
                     ...

                    ...
                        ...        
                            ...
                                ...
                                    ...
                                        ...

                                           ...
                                                ...
                                                    ...
                                                        ...
                                                            ...
                                                                ...
                                                                   ...  
                                                                        ...
                                                                            ...

                                                                                        ...
              ...
                      ...
                            ...
                                            ...
                   ...
                           ...
                                 ...
                                      ...
                                         ...
                                               ...    
                                                    ...
                                                         ...
                                                             ...
                                                                 ...
                                                                     ...
                                                                         ...
                                                                              ...
                                                                                  ...

Answer №1

To incorporate your JavaScript variable into the image element, you can use the following code:

document.write("<img src='"+imgNumber+".jpg' alt='' />");

By doing this, you will now have a random number in the image source.

Answer №2

Make sure the output is as follows:

document.write("<img src='"+imgNumber+"'.jpg' alt='' />");

Answer №3

In JavaScript, there are certain limitations you need to be aware of.

var imgNumber = randomInteger(9);//returns a random number from 0 to 9
document.write("<img src='imgNumber.jpg' alt='' />");

It's important to note that when you put 'imgNumber' in quotes, it becomes a string and not a variable.

To solve this issue, you should separate the string and the variable.

For example:

document.write("<img src='" + imgNumber + ".jpg' alt='' />");

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

Setting a default value for a select option in Angular 2

I am trying to set a default value for an option, acting as a placeholder using this method. It works in pure HTML, but when I implement it with the *ngFor attribute in Angular 2, nothing is selected. Here is the code I use in pure HTML: <select name= ...

Which is better for scrolling in Angular 2+: using HostListener or window.pageYOffset?

Which syntax is best for maximizing performance in Angular 2+? Is it necessary to use HostListener, or is it simpler to obtain the scroll position using the onscroll window event and pageYOffset? @HostListener('window:scroll', ['$event&ap ...

Should we define all public methods or prototype each method separately?

Typically, when I create a library, my approach is as follows: var myLibrary = (function() { return { publicProperty: 'test', publicMethod: function() { console.log('public function'); }, ...

The jQuery click event is failing on the second attempt

My PHP code dynamically generates a list, and I want to be able to delete rows by clicking on them. The code works fine the first time, but not the second time. HTML <li> <div class="pers-left-container"> <img src="<?php ech ...

What sets a module apart from a script?

As I delve into the depths of TypeScript documentation to grasp the concept of modules, particularly ES6 modules, I stumbled upon some interesting insights. typescript-modules - this documentation talks about typescript modules and highlights an important ...

Passing a variable from the server to the client function in Meteor with a delay

When I invoke a server function from the client side, it executes a UNIX command and retrieves the output on the server. However, I face an issue where the result is immediately returned as undefined by Meteor.call because the exec command takes some time ...

React: Issue with For Loop not recognizing updates in Hook's State

Recently, I successfully created a React application that displays each word of a sentence at a user-defined time interval for fast reading. However, I am now facing a challenge as I attempt to add a pause button functionality to the app. When I press the ...

Combining two classes into a single class using ‘this’ in JavaScript

I'm encountering an issue where I am unable to figure out how to extend from the third class. So, I really need guidance on how to call the A class with the parameter 'TYPE', extend it with C, and then be able to call getType() with class C. ...

Smooth scrolling feature malfunctioning in mobile view

While working on my website, I noticed that the smooth-scroll feature works perfectly on desktop browsers. However, on mobile devices, when I click on a link, it does not scroll to the correct position. It always ends up much lower than expected. Any idea ...

Ways to Determine the Height and Width of an Image Once it has been Adjusted for a View

Is there a way to retrieve the height and width of an image after it has been resized for a view? I have images that may vary in original dimensions, but users can resize them as needed. For example, this code from the console gives the client height: do ...

Utilizing HTTP POST method in vanilla JavaScript with AJAX

Having some trouble sending a post request to my PHP file as it keeps saying 'undefined index'. Here is my JavaScript code: document.getElementById("btn1").addEventListener('click', xh ); function xh(){ xhr = new XMLHttp ...

What is the best way to dynamically change the content of a div based on user selection?

When a user selects an option in the HTML, I want to display another div set to Block. I tried putting the OpenAskuser() function in a button, but it didn't work either. It would be ideal if we could achieve this without a button. Just have the displ ...

Troubleshooting 'Warning: Prop `id` did not match` in react-select

Having an issue with a web app built using ReactJs and NextJs. I implemented the react-select component in a functional component, but now I'm getting this warning in the console: Warning: Prop id did not match. Server: "react-select-7 ...

How can you locate and emphasize specific text within various elements using JavaScript?

Created a script to highlight linked text in another HTML page. <p>Click <span class="f1"><a href="#myModal" data-reveal-id="myModal">here</a>/span></p> <div class="leftspread"> <p class="table-caption"& ...

Why am I unable to insert data into the 'sessions' database using connect-mongo?

I am utilizing connect-mongo in conjunction with express-session, and the session data is successfully being stored in Mongo. However, I want to enhance the sessions collection utilized by connect-mongo in order to include my own fields on top of it. I h ...

Retrieve HTML classes within JavaScript textual templates

<!-- TEMPLATE UPLOAD --> <script id="template-upload" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-upload fade"> <td class="name"><span>{%=file.name%}</span></td> <td ...

Exploring date formatting in NestJs with Javascript

Currently, I am working with a ScrapeResult mikroOrm entity. I have implemented the code newScrapeResult.date = new Date() to create a new Date object, resulting in the output 2022-07-17T17:07:24.494Z. However, I require the date in the format yyyy-mm-dd ...

"Turn a blind eye to Restangular's setRequestInterceptor just this

When setting up my application, I utilize Restangular.setRequestInterceptor() to trigger a function that displays a loading screen whenever a request is made with Restangular. Yet, there is a specific section in my application where I do not want this fun ...

Exploring the Ins and Outs of Transition Testing in D3 v4

Previously, in older versions of D3, you were able to create unit tests that checked the state of a D3 component after all transitions had finished by flushing the timer with d3.timer.flush(). However, in D3 version 4, this has changed to d3.timerFlush(), ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...