How about having a surprise image pop up when you click a button?

I've been working on coding a button that can change the background of my webpage to display a random image. Initially, my code seemed functional, but it was only displaying the last image listed in my series of if/else statements. I suspect that using switch cases might be more suitable. My goal is for the code to select a random image by using Math.floor(Math.random()*3). Currently, I have set up an if statement as follows:

var randomImg = Math.floor(Math.random()*3);
   if (randomImg === 1) {
       $('html').css("background-image","url(http://i1-news.softpedia-static.com/images/news-700/Bomb-Threat-Prompts-Evacuation-of-Microsoft-s-Greek-Headquarters.png?1363255993)")
   }
   if (randomImg === 3) {
       $('html').css("background","url(http://www.zdeai.com/news/wp-content/uploads/sites/5/2013/10/d6802__tour-googles-luxurious-googleplex-campus-in-california.jpg)")
   }
   if (randomImg === 2) {
       $('html').css("background","url(http://upload.wikimedia.org/wikipedia/commons/8/84/Apple_Campus_One_Infinite_Loop_Sign.jpg)")
   }

Do you think utilizing a switch statement would be better for this scenario? Or perhaps incorporating a for loop could enhance the functionality?

Thank you for your assistance and input.

Answer №1

Instead of using if/else statements, you can try this approach:

var randomImg = (Math.floor(Math.random()*3));

images=new Array('http://i1-news.softpedia-static.com/images/news-700/Bomb-Threat-Prompts-Evacuation-of-Microsoft-s-Greek-Headquarters.png?1363255993','http://www.zdeai.com/news/wp-content/uploads/sites/5/2013/10/d6802__tour-googles-luxurious-googleplex-campus-in-california.jpg','http://upload.wikimedia.org/wikipedia/commons/8/84/Apple_Campus_One_Infinite_Loop_Sign.jpg');

 $('html').css("background-image","url("+images[randomImg] +")");

http://jsfiddle.net/7ExyY/ provides a simple way to store background images in an array and randomly choose one for display.

UPDATE: For a more dynamic solution, consider the following code:

var randomImg = (Math.floor(Math.random()*images.length));
console.log(randomImg);
$('html').css("background-image","url("+images[randomImg] +")");

http://jsfiddle.net/7ExyY/2/

This method allows for flexibility by not limiting the number of images in the array.

Answer №2

It is important to ensure that all if statements use == instead of =

number = 7

must be changed to

number == 7

Answer №3

= serves as an assigning operator. It is recommended to use ==, which functions as a comparison operator.

let randomImage = (Math.floor(Math.random()*3))
   if (randomImage == 1) {
       $('html').css("background-image","url(http://i1-news.softpedia-static.com/images/news-700/Bomb-Threat-Prompts-Evacuation-of-Microsoft-s-Greek-Headquarters.png?1363255993)")
   }
   else if (randomImage == 3) {
       $('html').css("background","url(http://www.zdeai.com/news/wp-content/uploads/sites/5/2013/10/d6802__tour-googles-luxurious-googleplex-campus-in-california.jpg)")
   }
   else if (randomImage == 2) {
       $('html').css("background","url(http://upload.wikimedia.org/wikipedia/commons/8/84/Apple_Campus_One_Infinite_Loop_Sign.jpg)")
   }

Answer №4

Make sure to properly differentiate between assignment and comparison.

To assign a value to a variable, use "="; to check a value against another, use "==".

var randomImg = (Math.floor(Math.random() * 3))
if (randomImg == 1) {
    $('html').css("background-image", "url(http://i1-news.softpedia-static.com/images/news-700/Bomb-Threat-Prompts-Evacuation-of-Microsoft-s-Greek-Headquarters.png?1363255993)")
}
if (randomImg == 3) {
    $('html').css("background", "url(http://www.zdeai.com/news/wp-content/uploads/sites/5/2013/10/d6802__tour-googles-luxurious-googleplex-campus-in-california.jpg)")
}
if (randomImg == 2) {
  $('html').css("background", "url(http://upload.wikimedia.org/wikipedia/commons/8/84/Apple_Campus_One_Infinite_Loop_Sign.jpg)")
}

Answer №5

Instead of writing a lot of code, you can simply use this snippet:

$("button").click(function(){

    var img = (Math.floor(Math.random()*3));

    allImg = new Array('link/to/img1.jpg','link/to/img2.jpg','link/to/img3.jpg');

    $('html').css("background-image","url("+allImg[img] +")");
})

Answer №6

=1 does not yield a true or false value since it is not being conditionally checked, so using ===1 would be more appropriate. The three equal signs ensure that the types are not converted to check against each other. Alternatively, utilizing a switch statement would offer greater efficiency in this scenario:

var randomImg = (Math.floor(Math.random()*3))
switch(randomImage)
{
    case 0:
    $('html').css("background-image","url(http://i1-news.softpedia-static.com/images/news-700/Bomb-Threat-Prompts-Evacuation-of-Microsoft-s-Greek-Headquarters.png?1363255993)")
    break;

    case 1:
    $('html').css("background","url(http://upload.wikimedia.org/wikipedia/commons/8/84/Apple_Campus_One_Infinite_Loop_Sign.jpg)")
    break;

    case 2:
    $('html').css("background","url(http://www.zdeai.com/news/wp-content/uploads/sites/5/2013/10/d6802__tour-googles-luxurious-googleplex-campus-in-california.jpg)")
    break;
}

The values have been changed from 1-3 to 0-2 to align with the range of randomImg.

You could also follow the suggestion by nevermind and consider creating an array for this purpose.

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

"JavaScript/jQuery: The pattern in the text does not align with the string

I am currently working on validating a text field with the specific data pattern of "I-MH-ABCD-ABC-1222". Below is the regular expression I have implemented, but unfortunately it is not functioning as intended. var router_added_sap = "I-MH-ABCD-ABC-1222" ...

What is the best way to create a new row at a specific index in an ng-repeat loop?

My Goal: I am aiming to insert a new row of ul after every 2 elements in my ng-repeat loop. For example: <ul class="col-sm-2"> <li><p>Automobile & Motorcycle</p></li> ...

Utilizing Jquery DataTables for server-side processing in an MVC 4 environment

My project involves using Twitter Bootstrap and Jquery DataTable to showcase data. I am searching for an MVC example similar to the one linked here. http://datatables.net/examples/data_sources/server_side.html Your assistance would be greatly appreciated ...

Which programming language is best suited for this task?

Seeking assistance with changing an image inside a div to another image with a simple mouse click. Wondering if this can be achieved through CSS or if jQuery would be the better option. Here is the code snippet: <div id="slideshow"> <img ...

The utilization of Display Flex resulting in the enlargement of the containing div

I am currently learning CSS and trying out some new things. I am looking to create a page with two side-by-side divs: one for the sidebar and the other for the main content. My goal is to have the sidebar take up 400px of width and allow the content part t ...

Create a unique bar chart plugin using Javascript/jQuery that allows users to drag and drop data

My current project involves developing a custom bar chart generator that must meet specific criteria: Input fields for entering data to display on the chart The ability to drag and resize bars once the chart is generated I've conducted research and ...

Separate the two divs with some added spacing

I am facing a challenge in creating a navbar with two regions split by white space. I attempted to use float:right and justify-content: space-between, but it doesn't seem to work as expected. My goal is to have site-header-right on the right side and ...

Utilize Javascript to extract and showcase JSON data fetched from a RESTful API

I'm attempting to use JavaScript to pull JSON data from a REST API and display it on a webpage. The REST call is functioning correctly in the Firefox console. function gethosts() { var xhttp = new XMLHttpRequest(); xhttp.open("GET", "https://10 ...

The inefficacy of the JQUERY validation plugin, AJAX, and PHP integration

After diving into learning AJAX for submitting forms, I've encountered a roadblock. The data I submit doesn't seem to reach the PHP file as expected, and I can't figure out why it's failing. Here's my HTML: <div class="col-md- ...

Changing the cursor while the onDrag event is active in ReactJs

I want to implement Drag functionality on certain elements in my application, but I am facing an issue where the cursor changes during dragging. How can I change the cursor specifically when onDrag is active? ...

Adjust the dimensions and position of the notification box using Twitter Bootstrap

I am struggling to center and adjust the size to 80% of an alert box, but the text-center class is not achieving this for me. <div class="text-center"> <div class="alert alert-info" style="width: 80%;" role="alert"> <i class="fa fa- ...

Is there a way to allow scrolling in only one direction using CSS?

I am facing an issue with resizing elements within a list. The requirement is that when the elements are resized, they should overflow the container only in the x direction. There must not be any scrolling in the x direction, but scrolling should be allowe ...

The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario: https://jsfiddle.net/0g1Lvk2j/20/ If you scroll to the end and close the last box by clicking on the orange box, the orange b ...

Expanding the <li> elements to create a wide horizontal navigation menu that fits within a 960 grid layout with 12 columns

I'm having trouble making the individual "li" elements inside the "nav" element stretch to fill a 600px space defined by the class "grid_8" in the HTML. I've tried setting width:100%; for the nav, li { width: 100%;} and various other solutions wi ...

Webpack failing to load jQuery correctly

In the process of transitioning my application.js application into smaller page bundles using SplitChunks, I have encountered a situation in my users/show.html.erb page where I am utilizing the following tag to import the specific chunk. <%= javascript ...

Alter the typography of the text that has been enhanced by Google

I am attempting to modify the default font of certain text that is processed through google-code-prettify within an angular directive. The structure of the template served by my directive appears as follows: <pre class= "prettyprint" style= "border:1p ...

What are the steps to design a curved gauge with a linear-gradient background?

Looking to create a fully responsive gauge using only CSS, ranging from 0-100% with a gradient color transition from green to red. After encountering issues with existing examples, I conducted tests and ultimately developed a solution that somewhat meets t ...

Having trouble getting the controller function to execute in Laravel 8

My goal is to create a dynamic dropdown list for countries and cities, but I'm facing an issue: Here's the code snippet from my view: <div class="form-row"> <div class="col-sm-6 ...

What is the most effective method for declaring a constant within a WebComponent?

After receiving questions, I included more details on how I'm utilizing the constants. The main issue I am encountering is that the constants are being added to the global object, which raises concerns about potential name collisions. I created a Web ...

The server-side PHP script may not always successfully respond to an Ajax call from the client

Whenever I try to access my index.html site, there are times when the Ajax request is made to call the PHP on the server in order to display the dynamic content. But for some reason, it only works intermittently when I manually refresh the page using the a ...