How to trigger a button tap with javascript? - javascript

I want to automatically trigger a tap on a button with javascript.
var submitButton = document.getElementsByName('name');
I tried the following and none of them worked.
submitButton.click();
and
const touchEvent = new TouchEvent("touchstart", {
touches: [touch],
view: window,
cancelable: true,
bubbles: true,
});
submitButton.dispatchEvent(touchEvent);
Neither worked.

Document.getElementsByName() returns a NodeList of elements (not a single element).
As far as the event, click should work just fine:
for (const elm of document.getElementsByTagName('button')) {
elm.addEventListener('click', (ev) => console.log(ev.target.textContent));
}
const buttons = document.getElementsByName('name');
for (const button of buttons) {
button.click();
}
<div>
<button name="name">one</button>
<button name="name">two</button>
<button>three</button>
</div>

Add an id to the above button with a onClick function.
Change the
document.getElementsByName('name')
to
document.getElementById('id')
Full Code:
Html:
<button id="btn" onClick="clicked()">
Click me
</button>
JS:
var btn=document.getElementById("btn");
btn.click();
function clicked() {
console.log("Clicked");
}
If you want to trigger multiple buttons with same class:
Html:
<button class="btn" onClick="clicked()">
Click me
</button>
JS:
var btn=document.getElementsByClassName("btn");
btn[0].click();
function clicked() {
console.log("Clicked");
}
For multiple button with same class, the return of the document.getElementsByClassName will return an array of object. In the above example, I have used the first element of that array, but if you want, you can loop through the array and trigger the click event.

document.getElementsByName returns a NodeList Collection of elements with a given name attribute in the document.
So your submitButton will be an array. So you have to dispatch the click event with submitButton[0].click()
var submitButton = document.getElementsByName('name');
submitButton[0].click();
function submitClick() {
console.log('submitClick')
}
<button name="name" onclick="submitClick()">Submit</button>

Related

why does the same event recognise different activeElements?

If I click a button the activeElement is the button.
If I leave an input box the activeElement is the Window.
If I leave an input box by clicking on a button the activeElement is ... both?
Why does the onfocusout event not register the same activeElement as the button?
Is there anyway I can access the click-on-button event from the function call of the inputbox-leave-event? ie can I ask, "Did you leave me for the lousy button?"
<button type="button" onclick = "myFunction()"> button </button><br>
<input type="text" onfocusout= "myFunction()"> </input>
<script>
function myFunction() {
console.log(document.activeElement);
}
</script>
You can add an event listener for the button inside the myFunction()
function myFunction() {
// console.log(document.activeElement);
var btn = document.getElementById("btn");
btn.addEventListener("click", function (event) {
console.log(event);
});
}
<!DOCTYPE html>
<html>
<body>
<button id="btn" type="button">button</button><br>
<input type="text" onfocusout="myFunction()" />
</body>
</html>
The activeElement read-only property of the Document interface returns the Element within the DOM that currently has focus.
Often activeElement will return a HTMLInputElement or HTMLTextAreaElement object if it has the text selection at the time. If so, you can get more detail by using the object's selectionStart and selectionEnd properties.
In addition, it is indeed possible to trigger a button click when leaving the input element, you just need to make sure to handle the onfocusout function, and use the code inside the function to trigger the click event, you can refer to here.
function onMouseUp(e) {
const activeTextarea = document.activeElement;
const selection = activeTextarea.value.substring(
activeTextarea.selectionStart, activeTextarea.selectionEnd
);
const outputElement = document.getElementById('output-element');
const outputText = document.getElementById('output-text');
console.log({ id: activeTextarea.id, selection});
}
const textarea1 = document.getElementById('textarea1');
const textarea2 = document.getElementById('textarea2');
textarea1.addEventListener('mouseup', onMouseUp, false);
textarea2.addEventListener('mouseup', onMouseUp, false);
<textarea name="textarea1" id="textarea1" rows="7" cols="40">This is Text Area One.</textarea>
<textarea name="textarea2" id="textarea2" rows="7" cols="40">This is Text Area Two</textarea>
The relatedTarget in the event will show you where it's leaving to
of course, you have to use addEventListener to access the event in the first place
But I think this demonstrates what you want to see
it'll definitely tell you
"Did you leave me for the lousy button?"
const button = document.querySelector('button')
const input = document.querySelector('input')
function buttonHandler(e) {
console.log('button clicked');
}
function inputHandler(e) {
console.log('leaving input for', e.relatedTarget?.tagName || 'window');
}
input.addEventListener('focusout', inputHandler);
button.addEventListener('click', buttonHandler);
<button type="button"> button </button><br>
<input type="text"> </input>

Why is adding event to button not working?

I try to add an EventListener to a button. Here is my code:
<button data-id="g/incider/perry">Kaufen</button>
<script type="text/javascript">
var button = document.getElementById('g/incider/perry');
button.addEventListener(
'click',
function() {
alert("test");
},
false
);
</script>
But the alert is not shown when the button is clicked.
I believe that you are new to the Javascript so will help you out here.
As you see your element <button data-id="g/incider/perry">Kaufen</button> has data-id attribute mentioned but you want to select the element by id as per your code document.getElementById()
Solution: document.getElementById() as the property named it searches for the id attribute in the element so you need to provide id to the element
<button id="uniqueID">Kaufen</button>
and then selecting it with,
const button = document.getElementById('uniqueID');
To Learn more about selectors in JavaScript you can check This Link
Try id instead of data-id.
<button id="g/incider/perry">Kaufen</button>
<script type="text/javascript">
var button = document.getElementById('g/incider/perry');
button.addEventListener(
'click',
function() {
alert("test");
},
false
);
</script>
If you want to use data-id for some reason you have to use the getAttribute() function to get the value of an attribute otherwise just stick with id.
const button = document.getElementById('g/incider/perry');
button.addEventListener('click', () =>
alert("test");
}, false);
<button id="g/incider/perry">Kaufen</button>

How I know which button been clicked in class of buttons?

I have the class of buttons and I want to know which one been clicked using JavaScript
<button class="editors">Edit</button>
<button class="editors">Edit</button>
<button class="editors">Edit</button>
so I want to know which button is clicked
You can pass this to your function and then you have a reference to the clicked button.
[...document.getElementsByClassName('editors')].forEach(x => {
x.addEventListener('click', function() {
myFunction(this);
})
});
function myFunction(el) {
console.log(el);
}
[...document.getElementsByClassName('editors')].forEach(x => {
x.addEventListener('click', function() {
myFunction(this);
})
});
function myFunction(el) {
console.log(el);
}
<button class="editors">1</button>
<button class="editors">2</button>
<button class="editors">3</button>
You can attach event listener to the document or your button's wrapper element/div and then use the event.target property. That way you use only 1 event listener, instead of attaching multiple for each element. This approach is called Event Delegation. You can check the different event properties here.
document.addEventListener('click', function(evt) {
let element = evt.target;
console.log(`Clicked button: ${element.textContent}`);
});
<button class="editors">Edit</button>
<button class="editors">Details</button>
<button class="editors">Delete</button>

How to change button text when clicked?

I am running my website off of squarespace and I have a button that says "DELIVER ME" but when you click it, I want it to say "G.T.F.O" while the next page loads.
I don't have a code for this and need help writing one.
function changeButtonText(DELIVER ME, G.T.F.O.){
if (this.value== "DELIVER ME"){
this.value = "G.T.F.O.";
} else {
this.value = "DELIVER ME";
}
}
changeButtonText();
I want the button to say "DELIVER ME" until you click it, then once you click it the button will say "G.T.F.O."
I want the button to say "DELIVER ME" until you click it, then once you click it the button will say "G.T.F.O."
Given this button:
<input type="button" id="myButton" value="DELIVER ME">
You could do it like this:
const myButton = document.getElementById("myButton");
myButton.addEventListener("click", function() {
this.value = "G.T.F.O."
});
Or, if the button is like this:
<button id="myButton">DELIVER ME</button>
You would do:
const myButton = document.getElementById("myButton");
myButton.addEventListener("click", function() {
this.innerText = "G.T.F.O."
});
function changeText() {
return document.querySelector("#button").innerHTML = "New text";
}
document.addEventListener("click", changeText);
<button type="button" id="button">Text</button>
most of the answer can solve your particular problem but I just want to add more information about selecting htmlElement.
in VanillaJS(pure Javascript) DOM. you can select element with 3 DOM method.
Select by ID's attribute
elem = document.getElementById("id")
Select by class attribute
elem = document.getElementsByClassName("class")
Select by TagName
elem = document.getElementByTagName("Tag")
and 1 more extra way which used.
elem = document.querySelector(selector)
selector can be one of ".class","#id", or "Tags"
Thanks
<button type="button" id="btn" onclick=changeButtonText()>deliver me</button>
<script>
function changeButtonText(){
document.getElementById("btn").innerHTML = "GTFO";
}
</script>

how to judge which button has been clicked using there className instead of ID

I have 100 buttons in a table having same class name but different id c-1,c-2,....,c-n <input type="button" class="btn-c" id="c-1" value="ADD">
how will i Know which button has been clicked using their className and whithout using onclick event on the each button
<input type="button" ... onclick="call_function(this);"
for simplicity let say I want to alert(button.id); on the click of any of the 100 buttons
If you have so many buttons, it makes sense to use event delegation:
$('table').on('click', '.btn-c', function() {
alert(this.id); // will get you clicked button id
});
This is optimal approach for performance standpoint as you bind only one event handler to parent element and benefit from child element event bubbling.
UPD. This is pure javascript version of the same code:
document.getElementById('table').addEventListener('click', function(e) {
if (/\bbtn-c\b/.test(e.target.className)) {
alert(e.target.id);
}
}, false);
Demo: http://jsfiddle.net/zn0os4n8/
Using jQuery - attach a click handler to the common class and use the instance of this to get the id of the clicked button
$(".btn-c").click(function() {
alert(this.id); //id of the clicked button
});
You need to attach an event to a parent element and listen for the clicks. You can than use the event object to determine what is being clicked on. You can check if it is the element you want and do whatever you want.
document.body.addEventListener("click", function (e) { //attach to element that is a parent of the buttons
var clickedElem = e.target; //find the element that is clicked on
var isC = (clickedElem.classList.contains("c")); //see if it has the class you are looking for
var outStr = isC ? "Yes" : "No"; //just outputting something to the screen
document.getElementById("out").textContent = outStr + " : " + clickedElem.id;
});
<button class="d" id="b0">x</button>
<button class="c" id="b1">y</button>
<button class="c" id="b2">y</button>
<button class="c" id="b3">y</button>
<button class="d" id="b4">x</button>
<div id="out"></div>
Note: this is not going to work in older IEs without polyfills.

Categories