Creating buttons in html css and javascript

JavaScript in Practice: Create dynamic buttons with JavaScript, HTML, and CSS 12 min read

Typically, we just need a few lines of code to create a button in HTML, pretty easy, huh? However, the fun part when working with front-end is actual applying JavaScript to make things become “dynamic”.

In this article, we will practice writing JavaScript along with HTML and CSS to create a dynamic button. The concept is rather straightforward, but just with this small problem, I want to demonstrate some essential concepts of the DOM, creating and styling a button with HTML and CSS, how to handle events and make things dynamic with JavaScript. Note that you should have basic HTML knowledge before going further. Here are some useful resources to learn HTML and CSS in case you didn’t do it:

Templates and visualized codes

Basic Format

If you’ve never worked with JavaScript, HTML, and CSS at the same time before, here is the template that helps you visualize how to write JavaScript and CSS code in HTML file:

Like the template above, you can write CSS inside the

tags on the and JavaScript code in

  • By putting , where style.css is the path of the .css file, in the head section (i.e., between the and tags), we’re telling the document to use the style sheet at the location referenced by the href attribute.
  • By putting , where script.js is the path of the .js file, in the body section (i.e., between the and tags), we’re saying that we want to run a script using the JS code at the location referenced by the src attribute.
Читайте также:  Java reflexion get method

HTML Buttons

We use button tag on HTML file to create a button, following with some of these optional attributes:

  • id : the button’s unique identifier within the page
  • class : the CSS class(es) used to style the button

The text enclosed between the button’s opening ( ) tags are the label that will display on the button. We can also access this text using the innerHTML property of the JS button object. (Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element’s opening and closing tag. By changing an element’s innerHTML after some user interaction, you can make much more interactive pages).

The basic syntax for an HTML button looks like this:

The image below shows few files of HTML code and the content they produce:

You’ve just created a button by using HTML! Now move on the main part!

JavaScript Buttons

First, let’s consider the following code:

Now, let’s walk through what it does (in case you haven’t get accustomed to DOM and event handler, do some research to have the taste first):

  1. document.createElement('Button') creates a clickable button object (createElement(‘Button’)) referenced by the variable name .
  2. clickMeButton.id = 'myButton' sets the button’s id to be myButton .
  3. clickMeButton.innerHTML = 'Click Me!' sets the button’s inner HTML (i.e., the label we normally see between the HTML button tags) to say “Click Me”.
  4. clickMeButton.style.background = '#3dfe3a' sets the button’s background color to green. To style multiple attributes of our button using a style class, we would write clickMeButton.className = 'myStyleClassName' instead.
  5. document.body.appendChild(clickMeButton) appends to the body of the document as a child.

Let’s say we want to modify the label on an HTML button element with the id myButton . We simply use the getElementById method and pass the desired element’s id as an argument:

This is another example of JavaScript code to create a button, what it will produce is some of the images below:

See, with JavaScript code, we completely replace the work of HTML code and also we can manipulate the color of the button through style.background attribute.

Styling Buttons with CSS

First, we want to define the style constraints for our button. We can do this in either of the two ways below.

1. Using an ID Selector

For instances where we want to apply a style to a single element within an HTML page, we use a CSS id selector using the syntax #identifier (where is the id of the element to style within the page). We then follow it with a pair of curly braces that contain the desired style constraints for all elements within the container that has that identifier. For example:

Читайте также:  Python tkinter проверить нажата ли кнопка

Note that we must put our CSS inside the style tags in the head section.

Let’s look at what happens when we style the element with the id :

We can access HTML id to manipulate inside CSS code by #yourId , thus the button is green because of this. And you also can see the pointer of you trigger on this button.

2. Using a Class Selector

Another way to apply the same styling to multiple elements is CSS class syntax .className (where is the name of our class). We then follow it with a pair of curly braces that contain the desired style constraints for all elements of that class. For example:

Let’s look at what happens when we style any element with the class :

You can see we can do the same thing when we access the CSS class element to manipulate the style of items. To access the CSS class, you use .className and instead of green color like before, I changed it to red. With literally ‘red’ color. You can change CSS color by 3 ways: Color Name such as Red, Blue, Green, etc…(which I just used), Hex Code #RRGGBB such as #FF6347 (which I used in few examples above), and Decimal Code (R,G,B) such as rgb(255,99,71). And also you can put id and class in the same place.

Combining HTML and JavaScript

We already know how to create a button in HTML and CSS. Now let’s combine them together:

Take some time to read through the following code:

When you are done with this, render this code above and see the result:

  • All three buttons have the background color styling from the button class, but each button has additional font styling specific to its distinct id.
  • The initial text label for htmlButton2 was I'm an HTML button! , but we used JavaScript to modify it to say I'm a modified HTML button! instead.

Click Events

When a user clicks a button, we call it a click event. Let’s look at using onclick and addEventListener to prompt an action in response to a click event.

Using onclick

The onclick event occurs when the user clicks on an element.

Now let’s using some features of JavaScript. Consider the following code:

The image below shows what the button looks like before and after it’s clicked:

Читайте также:  Directoryindex index php rewriteengine on rewritebase

Using addEventListener

The document.addEventListener() method attaches an event handler to the document.

Consider the following code:

The image below shows what the button looks like before and after it’s clicked:

Conclusion

In this article, we’ve been learning how to create a button by using JavaScript, HTML and also styling a button by CSS. Remember you can write HTML, CSS and JavaScript documents on the same file or in separate files. Events happen when users do something with your web, such as click on a link, scroll the mouse, type something, etc…addEventHandle and onClick are some of the ways that you can create an event on JavaScript through DOM (Document Object Model).

Источник

Create an HTML button using JavaScript

Create an HTML button using JavaScript

There might come a situation where you'll need to create an HTML button programmatically. In this post, we'll learn how to use JavaScript to create an HTML button.

The Basics

To keep it simple, we'll create a button that has the text Click here .

Here's how that looks like:

First, we used the document.createElement() method to create a new button element.

Then, we used the .innerText property to set the text of the button to Click here .

Finally, we used the .appendChild() method to add the button to the body of the document.

This will result in this HTML:

Going Further

In most cases, just changing the text of the button isn't enough. You'll probably want to change the type , name and perhaps add a class attribute.

Here's how to do this programmatically in JavaScript:

Event Listeners

After you've created your button, you'll want to add an event listener to it so that you can execute some code when the button is clicked.

Let's add an event listener to our button and listen for the click event.

 < alert("You clicked the button!"); >); document.body.appendChild(button); 

Now, once you click on this button, you'll get an alert saying You clicked the button! .

Conclusion

Sometimes, you'll want to create an HTML button programmatically. In this post, we saw how to create an HTML button using JavaScript, and how to alter the text of the button, type, name and class attributes.

We also learned how to add an event listener to our button and listen for the click event.

Hopefully you've found this post useful!

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Give feedback on this page , tweet at us, or join our Discord !

Источник

Оцените статью