/    Sign up×
Community /Pin to ProfileBookmark

Print random pictures in html file using js

Hi,
I have this js file index.js

“`
function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();

//insert the URL of images in array
randomImage[0] = “https://images.pexels.com/photos/858115/pexels-photo-858115.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500”;
randomImage[1] = “http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg”;
randomImage[2] = “https://images.pexels.com/photos/142497/pexels-photo-142497.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500”;
randomImage[3] = “https://images.unsplash.com/photo-1543877087-ebf71fde2be1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60”;
randomImage[4] = “https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg”;
randomImage[5] = “https://images.unsplash.com/photo-1501265976582-c1e1b0bbaf63?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60″;

//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);

//return the images generated by a random number
document.canvas.src = ‘<img src=”‘+randomImage[number]+'” />’;
}
“`

In my index.html file I want to print out the random pictures in a class called item4. I tried this but not working. Why? “`

“`
<div class=”item4″>
<center><h2 style=”color:green”> Random Image Generator </h2></center>
<h4> Click the button to generate and display random images on the webpage </h4>
<!– call user-defined getRandomImage function after 2 seconds –>
<button onclick = “setInterval(getRandomImage, 2000)”> Generate Image </button>
<br> <br>
<span id=”result” align=”center”> </span>
</div>
“`

Please help.

to post a comment
JavaScript

54 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumFeb 14.2022 — @Ashley128#1642474

Please use code tags when posting code: `your code here` or triple backticks. I edited your posting accordingly.
Copy linkTweet thisAlerts:
@cootheadFeb 15.2022 — Hi there Ashley128,

have a look at this example...

[b]Full Page View[/b]

https://codepen.io/coothead/full/MWOEpZm

[b]Editor View[/b]

https://codepen.io/coothead/pen/MWOEpZm

[i]coothead[/i]
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — it doesn't work. Failure here

(function( d ) {

'use strict';


var st;
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — can you write the codes in "lower" skills? I am new in this kind of programming. No skills at all.

Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — @Sempervivum#1642475
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — @Sempervivum#1642475

can you help me
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — @Ashley128#1642474

Don't worry, I was already busy creating some code including explanations in order to enable you to learn and improve your skills:

https://jsfiddle.net/Sempervivum/36bcafmr/

(unfortunately the forum doesn't allow for posting javascript, therefore I had to put the code on jsfiddle)

Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — In your case , you have the script inside the html. If I want to have a sep js file. How to do and link them?
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — I do this in order to create a test file quickly. You can easily place the javascript into an external file like you did alreay:

File index.js:
``<i>
</i> function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();

//insert the URL of images in array
randomImage[0] =
"https://images.pexels.com/photos/858115/pexels-photo-858115.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=1&amp;w=500";
randomImage[1] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg";
randomImage[2] =
"https://images.pexels.com/photos/142497/pexels-photo-142497.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=1&amp;w=500";
randomImage[3] =
"https://images.unsplash.com/photo-1543877087-ebf71fde2be1?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60";
randomImage[4] =
"https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg";
randomImage[5] =
"https://images.unsplash.com/photo-1501265976582-c1e1b0bbaf63?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60";

//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random() * randomImage.length);

//return the images generated by a random number
// There is no element document.canvas in your document:
// document.canvas.src = '&lt;img src="' + randomImage[number] + '" /&gt;';
// assign url of random image to src attribute of img tag inside the figure tag:
document.querySelector('figure.item4 img').src = randomImage[number];
}
let timer = null;<i>
</i>
`</CODE>
And include it in your HTML file:
<CODE>
`<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html lang="de"&gt;

&lt;head&gt;
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
&lt;title&gt;Random Image&lt;/title&gt;
&lt;!-- include javascript file, you will have to remove the underlines
in the script tags --&gt;
&lt;_script src="index.js"&gt;&lt;_/script&gt;
&lt;style&gt;
/* center all elements in figure: */
figure.item4 * {
text-align: center;
}
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;!-- A figure tag is designated to keep an image together with an explanation or caption: --&gt;
&lt;figure class="item4"&gt;
&lt;figcaption&gt;
&lt;!-- center tag is outdated, center content by use of CSS, see above: --&gt;
&lt;!-- &lt;center&gt; --&gt;
&lt;h2&gt; Random Image Generator &lt;/h2&gt;
&lt;!-- &lt;/center&gt; --&gt;
&lt;h4&gt; Click the button to generate and display random images on the webpage &lt;/h4&gt;
&lt;!-- call user-defined getRandomImage function after 2 seconds --&gt;
&lt;!-- this way a new timer will be started on every click on the button --&gt;
&lt;!-- &lt;button onclick="setInterval(getRandomImage, 2000)"&gt; Generate Image &lt;/button&gt; --&gt;

&lt;!-- Check if timer is already running and start it if it is not: --&gt;
&lt;button onclick="if (!timer) {timer = setInterval(getRandomImage, 2000);}"&gt; Generate Image &lt;/button&gt;
&lt;!-- Don't use &lt;br&gt; to create vertical space, use margin instead: --&gt;
&lt;!-- &lt;br&gt; &lt;br&gt; --&gt;
&lt;/figcaption&gt;
&lt;!-- img tag will keep the random image: --&gt;
&lt;img&gt;
&lt;/figure&gt;
&lt;/body&gt;

&lt;/html&gt;<i>
</i>
``
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — it doen't work
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — @Ashley128#1642486 Did you remove the underlines in the script tags in the head section?
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — i copied and paste everything
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — Copy&paste is not sufficient. You have to remove the underlines in the script tags in the head section:

https://pastebin.com/nZRpLDbc
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — I use your code, no work
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — Take a look at the console, probably you will find hints why it doesn't work:

Right click in the page, then choose "inspect element" and select tab "console".

Did you place the js file in the same folder as the html file?
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — Sorry, i did a misstake. I had the js file in a a subdir. Fixed now
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — I have a second problem.

I want to learn how to do this.

I saw some function

onfocus()

onblur()

How to apply to a textfield
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — It depends on the context. Which actions do you intend to take on focus and on blue?

Does the random image work now?
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — <form method="post" action="#">

<p>


<label for="Comments">Description*:</label>
<textarea name="comments" id="Comments" rows="5" cols="50" required></textarea>
</p>

<p>
<label for="Phone">Phonenr:</label>
<input type="tel" name="phone" id="Phone" />
</p>

<p>
<input type="submit" value="Skicka förfrågan" />
<input type="reset" value="Rensa fälten" />
</p>
</form>

Can these be ues for ex
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — the image works now
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — >Can these be ues for ex

Don't understand.

Take a look at this example:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#add_a_simple_listener

You can add an event listener to your input or textarea and take the actions you like.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — In the ex they use getElementById, but how do I access in my case?

I want onfocus on description and onblur for phonenummer
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — As you have already assigned an id ID to your form elements you can hand this over as a parameter to getElementById:
``<i>
</i>document.getElementById('Phone').addEventListener('focus', function(event){
console.log('input focussed');
// do any actions you like her
});<i>
</i>
``
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — should i write a function or where to place this
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — It all depends on your intentions, what you intend to do based on these events. Please explain the context.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — The idea is to

onfocus on description when leaving the field and

onblur for phonenummer when leaving the field
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — what to do in every case is not so important. The important thing is now to access to do anything
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — onfocus fires when you enter the input or textarea by clicking or tapping with the mouse or the finger tip.

onblur fires when you click or tap outside the input or textarea.

"fires" means that the anonymous callback funktion of the event listener is being called.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — So how can I realize these with codes
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — I am new on these js. Pls advise.
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — It's difficult to advice if I don't know what you intend to do with these events. I posted a code how to add an eventlistener to a form element. Doesn't this answer your question?
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — Onfocus makes description yellow background a

nd I blur makes description all to uppercase. Two button one of each
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — Two buttons? Possibly you understood something wrong. The events focus and blur fire automatically. Try this demo, I hope it helps you to understand:

https://jsfiddle.net/Sempervivum/nb7spmqw/1/
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — I put the code in index.js file. It does not work.

Did I miss anything?
Copy linkTweet thisAlerts:
@sibertFeb 15.2022 — > @Ashley128#1642525 I put the code in index.js file. It does not work.

You may have problem with cache. Clear cache and try again.
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — I was busy in the meantime with other subjects.

Did you add the HTMO too? You find it in the HTML tab of the jsfiddle.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — <section id="form">


<form method="post" action="#">

<label for="Comments">Beskrivning*:</label>
<textarea name="comments" id="Comments" rows="5" cols="50" required></textarea>
</p>
<p>
<label for="Phone">Telefonnummer:</label>
<input type="tel" name="phone" id="Phone" />
</p>

</section>

My html file look like this
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — Did you follow Sibert's advice? You can bypass the cache by reloading with Ctrl+F5.

If this doesn't help, take a look at the console.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — can i use the same index.js as before, just the the js script i got from you
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — ``<i>
</i> function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();

//insert the URL of images in array
randomImage[0] =
"https://images.pexels.com/photos/858115/pexels-photo-858115.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=1&amp;w=500";
randomImage[1] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg";
randomImage[2] =
"https://images.pexels.com/photos/142497/pexels-photo-142497.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=1&amp;w=500";
randomImage[3] =
"https://images.unsplash.com/photo-1543877087-ebf71fde2be1?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60";
randomImage[4] =
"https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg";
randomImage[5] =
"https://images.unsplash.com/photo-1501265976582-c1e1b0bbaf63?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=crop&amp;w=500&amp;q=60";

//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random() * randomImage.length);

//return the images generated by a random number
// There is no element document.canvas in your document:
// document.canvas.src = '&lt;img src="' + randomImage[number] + '" /&gt;';
// assign url of random image to src attribute of img tag inside the figure tag:
document.querySelector('figure.item4 img').src = randomImage[number];
}
let timer = null;

document.getElementById('Phone').addEventListener('focus', function(event){
// the element being focused
// is available in event.target.
// make background yellow:
event.target.style.backgroundColor = 'yellow';
});
document.getElementById('Phone').addEventListener('blur', function(event){
// the element being focused
// is available in event.target.
// make background white again
// and change text to upper case:
event.target.style.backgroundColor = 'white';
let val = event.target.value;
event.target.value = val.toUpperCase();
});<i>
</i>
``
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — Yes, you can.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — Looks ok?
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — Yes. Note that you need the previous HTML either as the script is referencing the input element.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — This is my contct.html file

<section id="form">


<form method="post" action="#">

<label for="Comments">Beskrivning*:</label>
<textarea name="comments" id="Comments" rows="5" cols="50" required></textarea>
</p>
<p>
<label for="Phone">Telefonnummer:</label>
<input type="tel" name="phone" id="Phone" />
</p>

</section>
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — i link the js script file in contct.html file
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — That's possible, however it seems to me that this form and the random images are completely different things. If so it would be advisable to use different js files IMO.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — no work at all
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — Can you help me
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — Did you click the input and type some text? When clicking the background should get yellow. When clicking outside afterwards the background should change to white again an the text to uppercase.

If this doesn't work, take a look at the console and check if there are any error messages.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

at text.js:1:33

got this error
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — You have to include the javascript **below** the HTML, right before the closing </body>.
Copy linkTweet thisAlerts:
@Ashley128authorFeb 15.2022 — It works now. Why put it at the end and not in the beginning
Copy linkTweet thisAlerts:
@SempervivumFeb 15.2022 — When adding the event listeners, the form elements are being referenced. And when putting the script in the head they do not yet exist and this results in the error that was reported in the console.

One remark: If you intend to discuss a subject completely different you better start a new thread.
×

Success!

Help @Ashley128 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.4,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...