Home > Blockchain >  I am trying to pass different link on a same variable using different buttons with html and js
I am trying to pass different link on a same variable using different buttons with html and js

Time:12-19

For my new project, I am trying to pass a link in a variable. I have buttons (multiple buttons let's say 50 buttons). So what it has to do is on button 1 click it should pass to var link = button1link.html and on button 2 click it should pass a variable to var link = button2link.html. making a specific function to each button is quite a long process so, In short, a specific button click should pass a specific link to var link . please help me out with it. Thanks :D

 <button id="button1"  onclick= "seturl();">click here </button>
var link = "linkOfButton1.html"

CodePudding user response:

You can put links into a data attribute of the button.

And add each click listeners by looping through the buttons.

let link

Array.from(document.querySelectorAll('button')).forEach(btn => {
  btn.addEventListener('click', () => {
    link = btn.dataset.link
    console.log(link)
  })
})
<button data-link="button1link.html">button1</button>
<button data-link="button2link.html">button2</button>

CodePudding user response:

Pass the venet to your seturl() and then you can make the link.

function seturl(e) {  
  const id = e.target.getAttribute('id');
  const name = id[0].toUpperCase()   id.slice(1);
  let link = "linkOf"   name  ".html";
  alert(link);
}
<button id="button1"  onclick= "seturl(event);">click here 1</button>
<button id="button2"  onclick= "seturl(event);">click here 2</button>

CodePudding user response:

Use a loop to set the links, location.href to forward the user to the specific page and also create the buttons (if they should be dynamic).

const links = ['https://example.com', 'https://google.com', 'https://stackoverflow.com'];

for (let link of links) {
    const button = document.createElement('button');
  button.innerText = 'Click here';
    document.body.append(button);
  button.addEventListener('click', () => {
    window.location.href = link;
  });
}

  • Related