Home > Software design >  How to open 3 different links, that is a different link each time on cycle on 3 clicks in javascript
How to open 3 different links, that is a different link each time on cycle on 3 clicks in javascript

Time:10-29

i need a logic to loop 3 urls on the cycle of 3 clicks . like after every 3rd click i want the link to be changed . .

       {
            if(Get_Cookie("pagecount") % 3 === 0)
            self.location.href="https://www.google.com";
            else
            self.location.href="https://www.wikipedia.com"";
            
       }

this is the logic i used to loop two different links on third click. but i need three different links to cycle. Here ,Get_Cookie("pagecount") returns the number of times im clicking the url on the next three clicks i want

self.location.href="https://www.facebook.com"";

CodePudding user response:

You can put the links in an array, and cycle through that. This has the benefit of being able to add as many links to the array as you want.

const links = ["https://www.google.com","https://www.facebook.com","https://www.stackoverflow.com"];
const timesToRepeat = 3;

let clickCount = 0;

document.getElementById("btn").onclick = (e) => {
  console.log(links[Math.floor(clickCount / timesToRepeat) % links.length]);
  clickCount  = 1;
};
<button id="btn">Click</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related