Ways to incorporate a while loop into a randomizing function

I've been diving into JavaScript and managed to create a website that displays random gifs when clicked from an array.

Now, my goal is to implement a while loop to prevent duplicate images from being shown consecutively. However, I seem to be facing a syntax issue and can't quite pinpoint where I'm going wrong.

HTML

<!DOCTYPE html>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<html>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="js/rand.js"></script>
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <head>
        <title>Randomizer</title>
    </head>

    <body> 

        <p>This image is random</p>
        <a href="#" class="click">
            <section> 
                <img>
                    <script>
                        getRandomImage()
                    </script>
                </img>  
            </section>
        </a>

    </body>

</html>

JavaScript

var randomImage = new Array();

randomImage[0] = "images/1.gif";
randomImage[1] = "images/2.gif";
randomImage[2] = "images/3.gif";

function getRandomImage() { 
    var number = Math.floor(Math.random()*randomImage.length);
    document.write('<img src="'+randomImage[number]+'" />');
}

$(function() {
    $('a.click').click(function(e) {
        e.preventDefault();
        var number = Math.floor(Math.random()*randomImage.length);
        $(this).html('<img src="'+randomImage[number]+'" />');
    });
});

Answer №1

Start by identifying the image being used:

function findImageNumber(){
    var imageNumber = parseInt($('img').attr('src').split("/")[1].replace('.gif', ""));
    return imageNumber;
}

Next, create a function that can be looped through (or use a while loop for simplicity)

function displayRandom(number){
    if(number != findImageNumber()){
        document.write('<img src="'+randomImage[number]+'" />');
    } else {
        displayRandom(number);
    }
}

Integrate the comparison loop into your main function:

function generateRandomImage() { 
    var number = Math.floor(Math.random()*randomImage.length);
    displayRandom(number);
}

Answer №2

const images = ['happy.png', 'sad.png', 'angry.png', 'surprised.png'];

function getRandomImage(imageArray, path) {
    path = path || 'images/'; // set default path
    const randomIndex = Math.floor(Math.random() * imageArray.length);
    const randomImage = imageArray[randomIndex];
    const imageString = '<img src="' + path + randomImage + '" alt="">';
    document.write(imageString); 
    document.close();
}

If you're interested in learning more about random image generation using JavaScript, check out this informative link:

Answer №3

To begin, create an array and include all the image names (or their corresponding indexes if you prefer), then implement a function similar to the one shown below:

var images = ["/picture1.jpg", "/picture2.jpg", "/picture3.jpg", "/picture4.jpg", "/picture5.jpg"];
function retrieveImage() {
  // Perform an action or return a placeholder image if there are no more images in the array
  //if (!images.length) doSomething(); 
  var image = images.splice(Math.floor(Math.random() * images.length), 1);
  return image[0];
}

Essentially, each time this function is called, it will output a random image name (or index) until all the images from the array have been used.

Answer №4

To keep the last image from the function, you can save it as a global variable instead of a local one. Global variables are accessible in all functions, while local variables are limited to the function they are defined in.

// Keep track of the last number outside the function
var lastNumber=0;
var imagesLength = randomImage.length; // calculate the length of images only once

function getRandomImage(){ 
    var number=0; // initialize the variable locally
    while( number == lastNumber){
        number = Math.floor(Math.random()*imagesLength);
    }
    document.write('<img src="'+randomImage[number]+'" />');
}

Regarding local and global variables, lastNumber is global, so it can be accessed within the function. On the other hand, var number is local and cannot be accessed outside the function, resulting in undefined if attempted.


A suggestion for improvement would be to avoid using document.write. Browsers may have issues with it, so it's better to pre-create an empty image:

<img id="RandomImage" src="transparent.png" />

Create a global variable to store the image reference and update the image source accordingly:

// Store image reference globally (before the function):
var Image2Random = document.getElementById('RandomImage');
// Update the image source instead of document write
Image2Random.src = randomImage[number]; 

This approach is more efficient as the script doesn't need to create a new image element every time. Manipulating the existing image source is faster and consumes fewer resources than inserting new elements into the DOM.

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

Can the swipe navigation feature be disabled on mobile browsers?

Currently, I am in the process of creating a VueJS form that consists of multiple steps and includes a back button for navigating to the previous step. The steps are all managed within a parent component, which means that the URL and router history remain ...

Tips for setting up Craigslist email forwarding through Node.js (receiving emails to a dynamically generated email address and redirecting them)

After extensive searching, I only came across this Stack Overflow post about Email Forwarding like Craigslist in Rails: Email Forwarding like Craigslist - Rails I spent a significant amount of time googling, but couldn't find any solutions using Node ...

Sending a parameter to the window.onload callback function

Is there a way to pass parameters from ModelAndView to a window.onload function in JavaScript within an HTML file? Here is an example of how it can be done: @RequestMapping(value = "/admin/printtext") public ModelAndView printtext() { ModelAndView mo ...

Unable to convert the BSON type to a Date in MongoDB

I am currently facing an issue while attempting to filter data stored in MongoDB utilizing parameters from the URL. Whenever I send the request, the server crashes and displays the error message: can't convert from BSON type string to Date I attemp ...

Removing White Spaces in a String Using JavaScript Manually

I have created my own algorithm to achieve the same outcome as this function: var string= string.split(' ').join(''); For example, if I input the String: Hello how are you, it should become Hellohowareyou My approach avoids using ...

An easy way to pass props to a component using useNavigate in React Router

Is it possible to send props directly to a component in React? const goToProjectPage = useNavigate(); useEffect(()=>{ ..... goToProjectPage("/projectpage"); //send props here },[]); ...

Display a new view upon clicking a button using AngularJS in a single-page web application

I am completely new to AngularJS and currently working on my first project. I apologize in advance if my question seems very basic. In my project, I have created a page using simple HTML with three buttons. When these buttons are clicked, I want to load v ...

Vuejs components that have checkboxes already selected out of the box

Hey there, I'm facing a small issue. Whenever I click on the areas highlighted in the image, the checkbox on the left gets marked as well. Any idea why this might be happening? https://i.stack.imgur.com/nqFip.png <div class="form-check my-5&qu ...

I have to ensure that a plugin is only loaded once its dependency has been loaded with RequireJS

Currently, I am utilizing the jquery.validationEngine.js plugin and facing an issue. It seems that jqueryValidateEnglish is unable to function properly unless jqueryValidateEngine is loaded beforehand. In my code for jquery.wrapped.validationEnglish2.js, ...

I am finding it difficult to navigate relative paths when using Master Pages

I utilized Visual Studio 2010 to start a fresh project with the Web Application template. Without making any modifications, please note that Login.aspx and Default.aspx both point to the same Site.Master master page in the website root directory. Addition ...

Activate the Bootstrap Jquery/Ajax inline editing feature by simply clicking on the Edit button

Seeking recommendations for a way to implement inline editing. When the edit button is clicked, I want the label's content to be replaced with an input text field that can be updated in my MySQL database. This is what my code looks like: <label s ...

Enhance your picture links with a:hover box-shadow styling

I've been struggling to add a box shadow on hover to a Facebook icon image. I assumed it would be straightforward, but as always, I was wrong. I'm working with a child theme in WordPress because I recently started, thinking it would be an easy wa ...

Attempting to refresh the choices in a dropdown list by sending a request via jQuery leads to specific

I have a Dropdown on my View that looks like this... <div class="editor-field"> @Html.DropDownListFor(model => model.CategoryId, new SelectList(new List<string>(), ""), "Select ...") </div> Within my controller, there is an action ...

Can file input buttons be custom styled?

Since I am using Material-UI, the traditional methods are not working for me. I have a form with two buttons positioned next to each other. One button is an "Upload File" input for users to upload a file, and the other is a submit button. I want both butto ...

Locate all buttons on the page that have an onclick function attached to them, and

I seem to have run into an issue. I am currently working with Java and WebDriver. My goal is to navigate to , locate the item "ipod", receive 4 results, and then compare them by clicking on the "compare" button beneath each item. However, I am encounteri ...

Discover the initial two instances of a specific element within a collection of javascript objects

Within my javascript arraylist, I am currently storing the following elements: list = [ {header: "header1", code: ""}, {label: "label1", price: 10}, {header: "header2", code: ""}, {header: "header3", code: ""}, {header: "header4", code: ""} ] My que ...

tips for expanding the size of your images

Hey there, I'm looking for some help with the code below. I need to increase the width of the images and remove the border of the slider div which is currently showing a white border that I want to get rid of. I am using JavaScript to display the imag ...

JSON data localization

I am currently in the process of developing a hybrid mobile application with PhoneGap as the platform. My goal is to localize the app's data so that it can be accessed offline. Essentially, I want all JSON data received from the API to be stored local ...

Manipulate text with jQuery

Is there a way to remove 'http://' or 'https://' from text using javascript? I am looking for regex solutions as well. This is what I have tried so far: JSFIDDLE HTML: <div class="string"></div> JS: $text = $('.s ...

Adding a specialized loader to vue-loader causes issues when the template contains personalized elements

My vue2 component is structured as follows: <template> <p>Hello world</p> </template> <script> export default { name: 'Example' }; </script> <docs> Some documentation... </docs> In addition, I& ...