Home > other >  change day by clicking on button
change day by clicking on button

Time:01-10

I want that each time I'm clicking on button that I see the Next day from day array list

The only way that I could get an answer is Math.random() to have different result each time I am clicking on button, but I want that show me the next day each time I am clicking on it.

function day() {
  var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
  document.getElementById("demo").innerHTML = days[Math.floor(Math.random() * 7)];
}
<button onclick='day()'>Click to see</button>
<span id="demo"></span>

CodePudding user response:

You could keep an array representing the days in the week while also keep an index to show the current day current.

On each click you will increment current value. The innerHtml value will be the current index (the % is being added to prevent out of bounce)

var days =['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
let current = 0;
function day(){
    document.getElementById("demo").innerHTML = days[current   % days.length];
}
<button onclick='day()'>Click to see</button>
<div id="demo">

</div>

CodePudding user response:

let index = Math.floor(Math.random() *7); //if you want always start from 'Monday' you can use 0 as startIndex
let days =['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
function day(){      
  document.getElementById("demo").innerHTML = days[index];
  index = (index 1)%7     
}
<button onclick='day()'>Click to see</button>
<h1 id="demo"></h1>

CodePudding user response:

To start from today you can use getDay which starts on Sunday

const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
let day = new Date().getDay(); //today
document.getElementById('addDay').addEventListener('click', function() {
  document.getElementById("demo").innerHTML = days[day   % 7]; // move the    to   day to show tomorrow on first click
})
<button id="addDay" type="button">Click to see</button>
<span id="demo"></span>

  •  Tags:  
  • Related