Html check which button is clicked

how to check if a button is clicked in javascript

Hello Everyone, today I’m going to share how do you check a button is clicked or not in JavaScript. Suppose you have added a search icon on your website and when a user will click on the search icon, the search box will appear. So this is very important and you must know about that.

There are many ways to check if a button is clicked or not in JavaScript . I shall share some ways.

Answer 1 :- Using Click Event

In the first example, I shall use the click event to check whether a button is clicked. First of all create a button with an id attribute. Then write javascript code between the tag.

 var seletBtn= document.getElementById('demoBtn'); selectBtn.onclick = function() 

Answer 2 :- Using addEventListener

You can use addEventListener instead of click event.

Demo Using addEventListener

  1. id Attribute : document.querySelector(«#demoBtn»)
  2. class Attribute :document.querySelector(«.demoBtn»)
  3. tag name :document.querySelector(«button»)
Читайте также:  Рисование диаграммы в php

Answer 3 :- Using onclick event

Answer 4 :- How many times a button is clicked?

First, create a html button with an id as id=»demoBtn» .

Then add the js code between the tag. First, store the button in a variable using js , create a variable and initialize it to 0.

How many times a button is clicked

In this post, I have explained how to check whether a Button is clicked using JavaScript. I hope you have learned something new in this tutorial.

Источник

How to check which button is clicked in JavaScript

Hello programmers, in this article you will learn how you can check which of the many buttons is clicked using forEach() method in JavaScript. Suppose, you have four buttons button 1 , button 2 , button 3 , and button 4 . Do something different for the button that users will click on.

The first thought that comes to your mind is to call a different function for each button. The example is given below.

    

If that’s what you think, then your answer is correct but elegant for just a few buttons. But, If you have a lot of buttons, the above approach is not elegant.

So, In this post, I shall detect which button is clicked using javascript loop dynamically.

Detect which button is clicked using for loop

let buttonList = document.querySelectorAll(".button"); for (let i = 0; i ); >
  1. Create button elements (as much as you want) with the same class named button .
  2. Store the all button elements into a variable as an array using querySelectorAll() method. eg. let buttons = document.querySelectorAll(«.button»);
  3. Create a for loop and inside the for loop just add a click event listener to all the buttons dynamically.

You can also pass a parameter. eg.

Check which button is clicked using forEach() method.

You can also use forEach() method instead of for loop. The example is given below.

let buttonList = document.querySelectorAll(".button"); buttonList.forEach(function(i)< i.addEventListener("click", function(e)< alert(e.target.innerHTML); >) >)

Источник

How to Detect Which Button is Clicked in Javascript

In this tutorial, you will learn how to detect which button is clicked in javascript. The first thought that will come to your mind would be, why not just add a click event listener to all the buttons and then let the event handler function execute whatever piece of code we want.

The answer is yes, you can do that. The above approach is fine if you have just a couple of buttons that you can easily select by using a document.querySelector() or document.querySelectorAll() method and attach click event listener to each of them. But if you have a lot of buttons, then the above approach is not elegant.

Detect Button Using Event Propagation

In such situations, it’s better to take advantage of event propagation. Event propagation defines the propagation of an event from the outermost element to the innermost element and vice versa. The three phases of event propagation are capturing phase, target phase, and bubbling phase.

Capturing phase is the first phase of event propagation. In this phase, the event propagates from the outermost element to the innermost element.

The target phase is the second phase of event propagation. In this phase, the event is reached to the innermost element.

The bubbling phase is the third phase of event propagation. In this phase, the event propagates from the innermost element to the outermost element.

The following example is pretty straightforward. We have three buttons and with the help of event propagation, we will detect which button is clicked by the user and display its id and inner text on the screen. Please have a look over the code example and steps given below.

  • We have one div element, three button elements, and one h1 element in the HTML file. The div element is just a wrapper for the rest of the elements.
  • The three buttons have unique ids ( btn1 , btn2 , btn3 ) and inner texts ( Login , Submit , Reset ).
  • The h1 element has “Result” as inner text which will be later replaced by our template string.
  • We have centered aligned the elements by using the style attribute on the div element.
  • We have also included our javascript file script.js with a script tag at the bottom.
  • We have selected only the h1 element using the document.querySelector() method and stored it in the result variable.
  • From event bubbling, you know that almost all events bubble up, that’s why we have attached a click event listener to the document because no matter what element you click, it will always go all the way up to the document .
  • Inside the event handler function, we are storing the target element in the element variable. This helps us in grabbing further details about the element who is responsible for initiating the event.
  • We are simply checking if the element is a button by using its tagName property.
  • If the element is a button, then we will create a template string that contains the button id and innerText .
  • We will set the template string as an inner text for the h1 element.
let result = document.querySelector('h1'); document.addEventListener('click', (e) => < let element = e.target; if(element.tagName == "BUTTON")< result.innerText = `$: $`; > >);

Источник

Check Whether a Button Is Clicked by JavaScript

Check Whether a Button Is Clicked by JavaScript

  1. Use onclick HTML Attribute to Check Button Click in JavaScript
  2. Use onclick as JavaScript Method
  3. Use addEventListener Method to Check Button Clicks

In JavaScript, the onclick method and the addEventListener are the most common way to manipulate an action.

We will use onclick as an HTML attribute to check if the button is clicked. Again, we will continue the check with the onclick method by manipulating the DOM, and later we will see the use of the addEventListener to understand if the button click is working or not.

Use onclick HTML Attribute to Check Button Click in JavaScript

For this instance, we will take a button tag element and add the attribute onclick .

The attribute will have a function called whenever the button is clicked. Though onclick is fully a JavaScript method, as an HTML attribute, it is pretty common to use for triggering a specified function on click event.

 html> head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>Testtitle>  style>  button  background: gray;  outline: none;  border: none;  padding: 10px;  border-radius: 3px;  color: white;  cursor: pointer;  >  style>  head> body>  button id="btn" onclick="clicked()">Click herebutton>  script>  const btn = document.getElementById('btn');  function clicked()  btn.style.background = "purple";  console.log("CLICKED");  >  script>  body>  html> 

In this example, the function clicked() has a code body that changes the style background from gray to purple whenever the button is clicked.

Use onclick as JavaScript Method

onclick in JavaScript focuses on only one event to call the callback function. This method also emphasizes executing a function body that is declared after the initiation of the method.

But first, the onclick method requires an object to be followed. The HTML element’s querySelector defines the object here.

 html> head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>Testtitle>  style>  button  background: gray;  outline: none;  border: none;  padding: 10px;  border-radius: 3px;  color: white;  cursor: pointer;  >  style>  head> body>  button id="btn">Click herebutton>  script>  const btn = document.getElementById('btn');  btn.onclick = function()  btn.style.color = "yellow";  console.log("CLICKED!");  >  script>  body>  html> 

Here, the occurrence of the click event outputs in the console as CLICKED! and the button style also gets to change its font color from white to yellow. The btn.onclick method sets off to run the corresponding function, and thus the change after the click is visualized.

Use addEventListener Method to Check Button Clicks

Usually, the addEventListener method is not supported by the older browsers, but it can punch on multiple events.

Here, we will use one event, click , and the function that the event will handle will fire the button to change. Also, we will print something in the console panel to be more sure about the event activity.

 html> head>  meta charset="utf-8">  meta name="viewport" content="width=device-width">  title>Testtitle>  style>  input  background: gray;  outline: none;  border: none;  padding: 10px;  border-radius: 3px;  color: white;  cursor: pointer;  >  p  background: white;  color: gray;  >  style>  head> body>  input type="button" id="btn" value="Click Here">  p id="after">p>  script>  const btn = document.getElementById('btn');  function getItDone()  document.getElementById('after').innerHTML = "I am clicked."  console.log("CLICKED!");  >  btn.addEventListener('click', getItDone);  script>  body>  html> 

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

Related Article — JavaScript Button

Related Article — JavaScript EventListener

Copyright © 2023. All right reserved

Источник

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