Home > Net >  Programming a button with javascript using outer files
Programming a button with javascript using outer files

Time:02-21

Hey guys im trying to program a button in javascript, I called a the button when the button is clicked but it doesnt seem to work. any help would be great. Thanks (this is my first time asking a question so please forgive if my format isnt correct. )

// HTML

<div>
  <button onclick = "page"  > Test button </button>
< /div>

// Javascript

function page () {
  <input type="button" onclick="location.href='https://google.com';" 
        value="Go to Google" />
}

CodePudding user response:

You need React to have HTML inside JavaScript in (more or less) the way you wrote it

It is also not recommended to have inline event handling (onclick etc)

You likely mean

window.addEventListener('DOMContentLoaded', function() { // when elements on page are available
  document.getElementById('page').addEventListener('click', function() { // when button clicked
    location.href = "https://google.com";
  });
});
<div>
  <button id="page" type="button">Go to Google</button>
</div>

CodePudding user response:

You can do this with just html if you don't want to use react

<button onclick="window.location.replace('https://www.google.com')">
  Click Me
</button>

CodePudding user response:

First of all you have to call the function onclick = "page()"

function page () {
    location.href = "https://google.com";
  }
<div>
      <button onclick="page()">Click Me</button>
</div>

CodePudding user response:

You can't just use plain HTML inside a vanilla JavaScript function.

With plain JS you can assign a DOM element Object to a variable and add an event listener that will trigger the function you create on click:

    const btn = document.querySelector("button");
   
    function redirectToGoogle () {
       window.location.replace('https://www.google.com')
    }

    btn.addEventListener('click', redirectToGoogle);

CodePudding user response:

ANSWER

  1. In HTML file, you didn't call page function on button onclick event.
  2. In JavaScript file, location.href is used to locate to another page when you are on the same page.

function page() {
  location.href = "https://www.google.com/" ;
}
<button onclick = "page()" >Test button</button>

  • Related