-1

Im using a function to return a string to a button onclick. That string contains a link to google. When I press the button, it does not redirect to google. Im very new to using html and java.

<button id="linkBtn" type="button" onclick="window.location.href = getGoogleLink();">Google</button>

<script>

 function getGoogleLink(){
        string google = "'https://www.google.com/'"
        return google;
    }

</script>

2 Answers2

1

Im very new to using html and java.

You mean JavaScript.

Please take a look at the following post. It handles redirection via JavaScript. How do I redirect to another webpage?

And please don't use the HTML event handler registration attribute onclick. It's bad practice. Add an ID to the DOM element and do everything inside your JavaScript.

(() => {
  
  window.addEventListener('load', () => {
    // get the button element from your HTML
    const btn = document.getElementById('btn');
    
    // register click listener
    btn.addEventListener('click', () => {
      window.location.href = "https://google.com/";
    });
  });
  
})();
<button id="btn">Redirect to Google</button>
Kluddizz
  • 703
  • 3
  • 8
0

you need to use location.replace('address').

for e.g.

<button id="linkBtn" onclick="redirect('https://www.google.com/')" type="button">Google</button>

<script>

    function redirect(url) {
        location.replace(url)
    }

</script>

At the top, I wrote a function to get URL and change windows location, URL came from:

onclick="redirect('https://www.google.com/')"
Ali Safari
  • 137
  • 6