Ask coding questions

← Back to all posts
HTML
WilliamXing (45)

How can you create a button in HTML? After that, how can you color it and make something happen when it's clicked?

Answered by SameeraMurthy (110) [earned 5 cycles]
View Answer
Comments
hotnewtop
SameeraMurthy (110)

Creating A Button

You can create a button in HTML

<button id="btn">Click Me!</button>

Basic Styling of the button

You need to use CSS to style the buttons.

button {
  background-color: green;
  color: white;
}

Events button (ex. On Click)

You need to use JavaScript to give it functionality.

let button = document.getElementById("btn");
button.addEventListener("click", function(){
  alert("Hello");
});

Hope this helps.

SameeraMurthy (110)

@WilliamXing, try putting the <script> tag after the button.
Like this:

<button id="btn">Click Me!</button>
<script src=“script.js”></script>
19wintersp (1121)

@WilliamXing You need to remove the first <script> tag, it's still there.

SameeraMurthy (110)

@WilliamXing, you have to remove the <script> tag that is above the button.

RYANTADIPARTHI (6001)

Solution

the first step is tp make a button. Try this code for that.

<button id="demo" onclick="myFunction()">Click me</button>

the onclick is for js purposes. Now, to color it.

<button id="demo" onclick="myFunction()" style="color: red background-color: lightgreen;">Click me</button>

now, that button's text is red. and background is lightgreen.

<script>
    function myFunction() {
        document.getElementById("demo").innerHTML = "I have been clicked";
    }
</script>

that's the js. Now, to piece them all together.

<button id="demo" onclick="myFunction()" style="color: red background-color: lightgreen;">Click me</button>

<script>
    function myFunction() {
        document.getElementById("demo").innerHTML = "I have been clicked";
    }
</script>

like that. All your requirements.
That should work

xxpertHacker (861)

To create a button, make a button element <button />, to color it, use CSS, to make something happen, use a CSS pseudo-class.

HTML:

<button>
    Buttons are things that you click, so... how about you click me?
</button>

CSS:

button {
    color: green;
}

button:active {
    color: red;
}

Now seriously, why do you need to know? Maybe you just need some documentation instead?

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

xxpertHacker (861)

Did this not help you?