Как сделать кнопку javascript в html
Перейти к содержимому

Как сделать кнопку javascript в html

  • автор:

Кнопка

Рассмотрим пример, как нужно обрабатывать нажатия кнопки в форме с помощью JavaScript.

Создадим простейшую форму.

На данный момент кнопка ничего не делает. Получим доступ к кнопке.

Далее следует создать код, который будет выполняться при нажатии кнопки.

Осталось подключить созданную функцию к переменной

При нажатии на кнопку появляется сообщение.

Идём дальше. Мы хотим получить текст, введённый пользователем в текстовом поле. Когда пользователь вводит текст, то у элемента input type=»text» в свойстве value появляется значение, которое и содержит текст пользователя. Таким образом, нам нужно сначала получить доступ к элементу страницы по идентификатору, а затем его свойство.

Теперь выводится сообщение, в котором содержится имя кота. Не помешает небольшая проверка, что текст был введён.

Третий шаг — выводить имена котов на самой странице. Мы уже приготовили список ul, к которому тоже можно получить доступ и добавлять дочерние элементы. Для получения доступа используем знакомый метод getElementById(). Для динамического создания нового элемента используется метод document.createElement(). После создания мы можем настроить элемент, например, прописав текст. Для текста элемента списка будем использовать переменную, которая содержит имя кота. Создав новый элемент, его необходимо добавить к родительскому элементу через appendChild().

Новые способы

В последнее время стали использовать другой код. Например, используют const вместо var, вместо onclickaddEventListener.

Также вместо getElementById() можно использовать querySelector(). А в addEventListener использовать другой формат вызова функции.

Day 8: Create a Button

In this challenge, we practice creating buttons in JavaScript. Check out the attached tutorial for learning materials.

Complete the code in the editor so that it creates a clickable button satisfying the following properties:

  • The button’s id is btn.
  • The button’s initial text label is . After each click, the button must increment by . Recall that the button’s text label is the JS object’s innerHTML property.
  • The button has the following style properties:
  • A width of 96px.
  • A height of 48px.
  • The font-size attribute is 24px.

The .js and .css files are in different directories, so use the link tag to provide the CSS file path and the script tag to provide the JS file path:

Submissions

This is a new style of challenge involving Front-End rendering. It may take up to seconds to see the result of your code, so please be patient after clicking Submit. The Submissions page contains screenshots to help you gauge how well you did.

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.

For example, let’s create a <button> that says "Click Me" using JavaScript:

  • 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 <body> 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 <button> 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.

Get 100 JavaScript Snippets Book for FREE ��

100 JavaScript snippets that you can use in various scenarios

Save 1000+ hours of research and 10x your productivity

Ezoic

report this ad

About

Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.

Free Code Snippets Book

Get my FREE code snippets Book to 10x your productivity here

Ezoic

report this ad

How To: HTML Canvas Buttons

Jake Pine

In this tutorial, I will walk you through creating interactive buttons on the HTML5 canvas. This tutorial is split up into three sections: Getting Familiarized with the Starter Code, Creating a Button Class, and Adding Event Listeners to the Canvas.

For this tutorial, I will assume a basic understanding of both JavaScript and HTML. While a thorough knowledge of HTML is not necessary, we will be using a base index.html file as well as basic HTML events.

The code snippets in this tutorial are written in TypeScript as it more clearly shows the types of variables and functions which will hopefully minimize confusion. If you are new to TypeScript or would prefer to see the code in pure JavaScript, all source code from this tutorial can be found at this git repo.

Now, onto the tutorial…

Getting Familiarized with the Starter Code:

The starter code for this project can be found here. I have created a basic index.html file with a head and a body. Inside the body, you can find the canvas we will be drawing on, and a link to our JavaScript file:

In our main.js file, I have laid out the basic structure of a canvas update loop:

The init function serves as a place to setup (initialize) any variables for the program, while the update function provides a place to update the scene and redraw every frame.

I went ahead and added to the update loop so that it draws a black background and draws the initial version of our button:

We are now able to see a black canvas with an orange ‘button’ on it:

Creating a Button Class:

I could teach you how to create a button at a specific location with a specific size and handle clicks for that area of the screen, but that wouldn’t be very scalable. Instead, I will walk you through the process of creating a container class for our button so we can easily create many buttons anywhere on the screen (and even allow for a moving button or one that grows and shrinks).

First, it would be good to decide what variables our button class will contain. Another way to think about this is: what might differ from button to button?

The features I have decided that vary between buttons are: text, button color, text color, position, and size. From this, we can create the following fields for our class.

Next, we should make a constructor for our button class. Since the main things that define separate buttons to me is the text and the styling, I made the constructor with only those parameters. I created separate functions for setting the position and size of the button (which also allows for easier animating of the buttons).

This class now holds all of our data for a button, but how do we draw it? We could access all of its fields individually, and draw it using the code we had in main.js prior, but again, that wouldn’t be very scalable. Let’s create a draw method in Button so each button knows how to draw itself.

Here I have adapted the drawing code from main.js to use the fields in our class instead of the hardcoded values:

Now in our main.js it is time to create an instance of our Button class. We will initialize our button in the init function:

All we need to do now in order to draw our button is to call our button’s draw method in the update loop:

If we look at the result, we can see that our button is drawing once again and we can tweak the values in our developer console and watch it update live.

If you are following along, it might be a good exercise to try implementing button borders (ie. color, thickness, etc…) yourself.

Adding Event Listeners to the Canvas:

Now we’re getting to the main show… almost.

Before we add our button clicks, I suggest we think about the way we call draw on our button. The way we have it currently, we will need to call that function for every button in our scene. Instead of cluttering our code with all of these button.draw(c); lines, let’s create an array to store our buttons.

This way we are able to cleanly loop through all of our buttons and call their draw methods:

In order to add functionality to our buttons, we will need to add two things to our Button class. The first is a method that checks if a given position is within the bounds of the button (this will make it very easy to check if the mouse clicked on a button).

The second is a function that should be called when the button is clicked (aka what the button does). Since this function will vary for each button, I will treat it as a field of Button with the type of a void lambda function.

For our ‘Start Game’ button, I made the following lambda to log “Start Game!” whenever the button is clicked:

Now we are ready to add our event listener. Our event listener will detect anytime the canvas is clicked, determine the mouse position on the canvas, and call the onClick method of all (if any) buttons that the mouse was over when the click occurred.

Now we can see the message “Start Game!” in our console whenever we click our button.

Wrapup:

If you would like an exercise to try to build off of what I covered, my suggestions would be to make buttons change color when hovered over or clicked on. If you are not very familiar with HTML Events, this may be a helpful resource.

All source code can be found here, and live versions of each of the three stages of development can be found here.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *