How to make button in 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:

Читайте также:  Text decoration none javascript

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.

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:

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:

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).

Источник

JavaScript programmatically create an HTML button

Sometimes you need to create an HTML button programmatically as a result of some code execution. You can easily create a button using JavaScript by calling on the document.createElement("button") method.

  • First, you call the document.createElement("button") and assign the returned element to a variable named btn .
  • Then, assign the "Click Me" string to the btn.innerHTML property
  • Finally, use document.body.appendChild() to append the button element to the tag

The code below shows how this can be done:

You can append the button element that you’ve created with JavaScript anywhere inside your HTML page by using the appendChild() method.

You can also set the button’s name , type , or value attributes as required by your project. Sometimes, you need to create a type='submit' button for forms:

The code above will create the following HTML tag:
 Finally, if you want to execute some code when the button is clicked, you can change the onclick property to call a function as follows:
or you can also add an event listener as follows:
 And that’s how you can create a button programmatically using JavaScript.

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

How to Create Button in JavaScript

Developers mostly want their web pages to be attractive and make them interactive. For this purpose, buttons are added to the web page. For instance, when there is a need to send or receive data, including click events for added functionalities for the user while registering or signing in to an account. In such cases, buttons allow the end-user to perform various functionalities smartly.

This blog will explain the methods to create buttons in JavaScript.

How to Create Button in JavaScript?

To create button in JavaScript, the following methods can be utilized:

The following approaches will demonstrate the concept one by one!

Method 1: Create Button in JavaScript Using “createElement()” and “appendChild()” Methods

The “createElement()” method creates an element, and the “appendChild()” method appends an element to the last child of an element. These methods will be applied for creating a button and appending it to the Document Object Model(DOM) that needs to be utilized, respectively.

Syntax

document. createElement ( type )

element. appendChild ( node )

In the above syntax, “type” refers to the type of element that will be created using the createElement() method, and “node” is the node that will be appended with the help of the appendChild() method.

The following example will explain the stated concept.

Example

Firstly, a “button” will be created using the document.createElement() method and stored in a variable named “createButton”:

Next, the “innerText” property will refer to the created button and set the text value of the specified button as follows:

Lastly, the “appendChild()” method will append the created button to DOM by referring to the variable in which it is stored as an argument:

The output of the above implementation will result as follows:

Method 2: Create Button in JavaScript Using “Type” Attribute of “input” Tag

The “type” attribute represents the type of input element to display. It can be used to create a button by specifying “button” as the value of the type attribute of the input tag.

Syntax

Here, “button” indicates the type of the input field.

Check out the below-given example.

Example

Firstly, we will use an input tag, specify its type as “button”, and value as “Click_Me”. As a result, a button will be created. Furthermore, it will trigger the “createButton()” function when clicked:

In the JavaScript file, we will define the “createButton()” function which will generate an alert box when the added button will be clicked:

Output

The discussed techniques to create a button in JavaScript can be utilized suitably according to the requirements.

Conclusion

To create a button in JavaScript, “createElement()” and “appendChild()” methods can be applied for creating a button and appending it to be utilized in the DOM. Another technique that can be used to create a button is defining an input type and adding the associated functionality. This article demonstrated the methods to create a button in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

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