Question

How do I make a html button activate javascript? For example, if I make a button and i click it, it activates a javascript code that confirms ("Hi"). Help would be appreciated!

And if you actually want me to give an example, I am new to this and this is what i have tried:

<!DOCTYPE html>
<button type="button">This is the button</button>
<script language="javascript"> 
confirm("hi")
</script>
Was it helpful?

Solution

You should search about events. In your case the click event to be specific. You have to handle the button's click event, like this:

<input type="button" value="Click Me" id="myButton" />

Then the script:

document.getElementById("myButton").onclick = function()
{
    window.alert("Hi there!");
}

Demo.

This is the simpler way of doing this. Here's some references for further information:

Good luck.

OTHER TIPS

You need to bind an event listener to the button element (either via JS or as a tag attribute... for learning, I'd suggest the former), and use alert to display the message.

I'm not going to give you the code because that's not what SO is about.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top