Fred Brack   Fred Brack  
Raleigh, NC
Picture of the Cape Hatteras lighthouse

Interfacing JavaScript With Buttons
by Fred Brack
Updated

This is not a full tutorial on JavaScript interfacing with buttons but rather an introduction and reference to give you some ideas as to how to get started with some basics.  I created this web page to help me document my understanding of JavaScript dates as I progressed from novice to intermediate user ... and because I like to document stuff for others!  I hope you find it useful.

Buttons in HTML

The complete set of options for the HTML button tag is defined at w3schools.  Basically a default button (which does nothing here) looks like this:

and is defined simply as:

<button>Push my button!</button>

To get the button to actually do something, you have to add attributes such as type and value (but that's not our purpose here!).  Or you can specify a JavaScript action to take when the button is pushed by specifying the onclick option.

Using the onclick Event

By specifying onclick in the definition of a button, you are directing the browser to invoke some JavaScript whenever the button is clicked.  You can specify a complete JavaScript statement right there, or invoke a function.  Let's start with a simple direct specification of some JavaScript -- really basic!  And you may click the buttons from now on.


<button onclick='alert("Hello!")'>Click me</button><br>

You can get fancy, if you wish, as long as you keep it to one statement.

<button onclick='document.querySelector("#onclick").style.color="red"'>Change Header to Red</button>

Let's walk through the JavaScript on that one.

You can use the same technique to invoke a JavaScript function, which would allow more processing.  This example shows how you could toggle the wording of the button after performing some action.

<button onclick="toggle()" id="togglebtn">Change Header to Red</button>
<script>
function toggle() {
  var x = document.querySelector("#togglebtn");
  if (x.innerHTML == "Change Header to Red") { 
    document.querySelector("#onclick").style.color="red"
    x.innerHTML = "Change Header to Black"
  }
  else { 
    document.querySelector("#onclick").style.color="black"
    x.innerHTML = "Change Header to Red"; 
  }
}
</script>

Opening Another Window

Another good example of using JavaScript with a button would be to cause another window to open.  You can do this in straight HTML, particularly while exercising the submit option; but JavaScript would, of course, give you more control.  We are just using a simple example here to take you to a page which shows you all the options you can use with window.open.

<button onclick='window.open("https://www.w3schools.com/jsref/met_win_open.asp","_blank")'>Launch another page</button>

 

Fred