show a variable called - Random

Hey there,

I've been struggling with a bug and despite multiple attempts, I can't seem to find a solution :(

I want a month to be displayed when clicked, and then on another click, a different month should appear without repeating the previous one.

Here's what I have so far:

As a beginner, I tried searching on Google but couldn't find an answer to my question.

function randomMonth() {
var months = "January, February, March, April, May, June, July, August, September, November, December".split(',');
var randMonths = [];

while (months.length) randMonths.push(months.splice(Math.random()*months.length, 1)[0]);
document.getElementById("month").innerHTML = randMonths;

 }
<button onclick="randomMonth()">Try it</button>

<p id="month"></p>

Thank you for your assistance :)

Answer №1

Here is a simple way to generate a random month:

function getRandomMonth() {
  var months = "January,February,March,April,May,June,July,August,September,October,November,December".split(',');
  var month = months[Math.floor(Math.random()*months.length)];
  document.getElementById('current-month').innerHTML = month;
}
<button onclick="getRandomMonth()">Generate Random Month</button>

<p id="current-month"></p>

Answer №2

To achieve this, one can use the following method to create an empty array to store each month and check if it has already been displayed.

var tbl="janvier,février,mars,avril,mai,juin,juillet,août,septembre,novembre,décembre".split(',');
var randMois=[];

function randommonth() {
  var mois = tbl.splice(Math.random()*tbl.length,1)[0]; 
  console.log(randMois,mois)
  if(randMois.indexOf(mois)==-1 && randMois.length < tbl.length){
       randMois.push(mois)
       document.getElementById("mois").innerHTML = mois;
  }else{
      console.log("month already displayed",mois)
  }
 
 }
<button onclick="randommonth()">Try it</button>

<p id="mois"></p>

code sample - https://codepen.io/nagasai/pen/Yayxzj?editors=1010

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

Best practices for filtering data in an array of objects with multiple tags using React.js

const information = [ { id: 1, name: Dave, city: Elmwood, state: California }, { id: 2, name: Sarah, city: Lakeview, state: Michigan }, { id: 3, name: Emily, city: Riverside, state: Ohio }, { id: 4, name: Alex, city: Hillside, state: Texas }, { i ...

Tips on modifying the style of a specific React component without affecting the others

In my attempt to modify a single style property of a specific React component upon clicking it, I encountered an issue where the changes applied to every instance of that component. Despite consulting the React tutorial and various sources for solutions, I ...

Tips for modifying navbar appearance as user scrolls?

I am currently working on a website using Bootstrap 4. The goal is to create a navbar with a transparent background that transitions to white smoothly when the user scrolls down. I want the navbar to return to its initial state when the user scrolls back u ...

Utilizing sharejs to enhance collaborative editing with contenteditable sections

Is it possible to integrate sharejs with contenteditable elements such as <div contenteditable="true">Content <b>with html</b></div> containing HTML content? Are there alternative approaches for Operational Transformation (OT) whe ...

jQuery is unable to locate the FireBreath object

Currently, I am in the process of developing a web video player by using Firebreath to compile my C/C++ codec as a browser plugin. The plugin has been successfully loaded and is functioning properly (start, stop video, etc.). My next goal is to enable full ...

Ways to halt a CSS animation when it reaches the screen boundary

I put together this demo: By clicking, a red box falls down. The issue arises when trying to determine the screen size using only CSS. In my demo, I set the box to fall for 1000px regardless of the actual screen height. Here is the keyframe code snippet ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

The concatenation of Ajax results appears to append to the existing data

My ajax function handles uploading comments to a form, which then returns the same string. If successful, the comment is added to a comment box and the input text is cleared. The issue arises when a user adds another comment; the new comment is appended w ...

Discovering the bound ASP.NET AJAX event handlers for a specific DOM element

I am currently working on customizing a pre-existing ASP.NET 3.5 AJAX web application, specifically SharePoint 2010. Unfortunately, I do not have the ability to modify the source code. My task involves adding a click event handler to act as the first even ...

Disabling the scrollTop() effect following a click event with onClick()

Utilizing the scrollTop() event to toggle the visibility of a div at a specific position and also using the onClick() event to permanently hide the div. While the events are functioning properly, an issue arises when scrolling the page causing the div to r ...

Having trouble uploading files larger than 1MB with the combination of apollo-server-micro and NextJS

I'm in need of assistance with a specific issue. I've been attempting to upload an Excel file that is approximately 3MB in size from the client side to the API by first converting it to a DataURL and then sending it as a string. This method works ...

Drawing a line at each segment in a tube geometry using three.js

I have generated a tube shape with 200 coordinates from an external JSON file. See the code snippet below. function plotPath() { var obj = getPath(); var segments = obj.path.length ...

React Intersection Observer not functioning properly

Hey there! I'm trying to create an animation where the title slides down and the left element slides to the right when scrolling, using the intersection observer. Everything seems to be fine in my code, but for some reason it's not working. Any t ...

In order for data with two fields to be displayed correctly in an angular.js table, it must be shown twice

Within my angular.js table, data is being received and stored in a variable called dataArr. var dataArr = [ 0: "aaa", 1: "bbb" ] I have a condition that if the length of the data is greater than 0, it must be displayed twice in the table structure. For i ...

Tips for sending an extra parameter to the callback function when using the loader.parse method in Three.js

The Parse method of the Loader object in three.js allows you to specify a callback function that will be triggered upon completion of the parsing process. This callback will receive a unique argument which represents the parsed object. However, I am encou ...

What is the best way to split the vertices of a mesh in Three.js?

Is there a way to disassemble the vertices of a Three.js mesh? I am interested in tearing apart a 3D object using mouse input. Recently, I developed a GLSL vertex shader for this web application that shifts the vertices of a mesh based on the brightness of ...

Restricting the amount of requests per user within a single hour [Node.js]

As I work on developing a server side application using Nodejs and Express, one thing that crosses my mind is limiting the number of requests per user within a specific time frame to prevent malicious hackers from overwhelming the server with spam. I&apos ...

What is the best way to include an Interval in a button element?

I am currently working on developing an application that will automatically take a picture every minute using the camera. I want to implement a button tag with an interval so that when the application is running, it will capture an image every minute. i ...

Unable to "serialize" geoJSON information

While working with Leaflet JavaScript, I am attempting to retrieve data directly from GeoServer using an Ajax link. To display it nicely in a DataTables table, I need to convert it into JSON format as per DataTables instructions. However, I keep encounteri ...

Tips for minimizing a collection of objects?

Currently, I am working on developing a unique quiz format where there are no correct or incorrect answers; instead, responses are given a score ranging from 1 to 4. Each question falls under one of four distinct categories (such as cat, dog, rabbit, alpa ...