You're browsing the tag: JS

Tutorials

Javascript: Random Image Generator

I wrote a tutorial on generating random links with javascript some months ago. Recently, a person requested to show how to show this method but with images. This is why I’m writing this tutorial about how to create a random image generator.

The first thing you need to do is create an array with the URLs of the images you’re going to use. There are two common ways to do this, as you saw on the random link tutorial.

The condensed array:

Or the regular array:

You can use any of these two methods. The next step is to create the function that will generate the images using a native random method.

And that’s it! All that’s left for you to do is to combine all the code (showed below), which would display the image and every time you refresh the page, a random image from your array will appear.

DEMO

Here’s the complete code:

 

If you have any questions, don’t hesitate to leave a comment.

 

Programming / Tutorials

Javascript: Random Link Generator

This is a very simple code that you can use to generate random links. You can create a button, link, image with this function, which will randomly choose between the specified URLs to visit.

The first thing would be to create the array with the URLs There are two common ways to do this: The condensed array:

Or the regular array:

You can use any of these methods to create the generator, the next step is to create the function that will generate random links using the javascript Math.random method.

And that’s it! All that’s left is to add the HTML portion of the code, it can be a button, image, link, etc. I will use a link for this example:

This code can be modified to do many different things. For example, if you would like to display random quotes on your website, you could modify this code a little bit to make that happen. I will create a separate tutorial for that, though. Here’s the complete code from this tutorial:

If you have any questions, don’t hesitate to leave a comment.


Follow @_NicoleJeanette