Home > other >  assign one function to 3 buttons directing to outside websites
assign one function to 3 buttons directing to outside websites

Time:10-30

I found similar answers but not exactly what I was looking for. how can I handle 3 buttons with 1 function? how to integrate document property into the solution?

Here is the code:

function gotoUrl() {
  window.location.assign("https://www.google.com/")
}

function gotoUrl1() {
  window.location.assign("https://www.yahoo.com/")
}

function gotoUrl2() {
  window.location.assign("https://www.youtube.com/")
}
<button class="one" onclick="gotoUrl()"> Google </button>
<button class="two" onclick="gotoUrl1()"> yahoo </button>
<button class="three" onclick="gotoUrl2()"> Youtube </button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can enter params into a function, which is a variable included in a function when it is run. Here is your modified code only using 1 function:

<!-- html -->
<button class="one" onclick="gotoUrl('https://www.google.com')"> Google </button>
<button class="two" onclick="gotoUrl('https://www.yahoo.com')"> yahoo </button>
<button class="three" onclick="gotoUrl('https://www.youtube.com')"> Youtube </button>
// javascript
function gotoUrl(link /*link is a param, now we can use it as a variable in our function*/){
     window.location.assign(link)
}

w3schools on params : https://www.w3schools.com/js/js_function_parameters.asp

CodePudding user response:

function gotoUrl() {
              window.open("https://www.google.com/")
            }
            
            function gotoUrl1() {
              window.open("https://www.yahoo.com/")
            }
            
            function gotoUrl2() {
              window.open("https://www.youtube.com/")
            }
<button class="one" target="_blank" onclick="gotoUrl()"> Google </button>
       <button class="two" target="_blank" onclick="gotoUrl1()"> yahoo </button>
       <button class="three" target="_blank" onclick="gotoUrl2()"> Youtub </button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.

syntax:

window.open(URL, name, specs, replace)

For More details Click Here: window.open

  • Related