How to click a button in Javascript? - javascript

Super basic question. How do I trigger the clicking of a button in javascript?
Here's the relevant code
<button class="button--unstyled link-without-visited-state inline-block font-size-inherit topcard-see-more-link" type="button">See all</button>
I know the solution is something like this
document.getElementById("myButton").click();
I'm new to this unsure what from the code I would replace with "myButton" and if anything goes inside the click parentheses

First, if you're using getElementById, you need to give your element an Id. Without which, it's not going to work, so in your case:
<button id="myButton" class="button--unstyled link-without-visited-state inline-block font-size-inherit topcard-see-more-link" type="button">See all</button>
Next, we'll set up the button so it can be referenced later
const myButton = document.getElementById('myButton');
Finally, we'll add a click event listener:
myButton.addEventListener('click', myFunction);
This is going to add a click listener to our button and fire the myFunction function when it's clicked.
There's a couple of others ways to achieve the same thing. I would suggest checking out MDN for more details!
https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event

Your code is looking for an element with id="myButton", but it is probably returning null; it will work if you add the id property to the button:
<button id="myButton" class="......"></button>

Related

difference between having a click handler on a button or on its parent?

Between
<button onClick={...}>Click me</button>
and
<span onClick={...}>
<button>Click me</button>
</span>
are there any differences for the user? I know that the click event will always bubble up to the span element, but are there any accessibility issues or unintended consequences that could arise from this?
There is a massive difference!
If you tab to a <button> so it is focused you can activate it using Enter and it will activate the click handler. It will not do this with a <span> (even if you add tabindex="0" to the <span> so it is focusable).
Also having a click handler on a <span> around a <button> will cause issues as you then have nested active elements. This means that when you click on the <button> that is within a <span> there is no way of knowing which element is supposed to fire an event (is it the <span> click handler or the <button> click handler?)
The question is, why do you want to attach the handler to the <span> as it may be that there is a better way to do what you are attempting. Let me know and I will see if I can help you structure things better / work around the problem!
since your question is about accessibility, you sure shouldn't do this because you have a native element for "clicking things" in HTML, but if you insist you can make a span work as a button by:
adding the role='button' attribute
handle the aria-pressed attribute value
define a value for tabindex attribute.
if you didn't do this the screen readers users will have a difficult time in your website
this link contains an example how button can be considered a div with extra attributes: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/button_role
In that setup, you should be fine. If however you had a <span> inside of the <button>, then that's when you'll run into issues because a button should not contain children elements, only the value.
<button type="button" onclick="alert("Yo");"></button>
= works
<button type="button"><span onclick="alert("Yo");"></button> = fails
And then I believe Firefox handles these events differently to Chrome, but the latest builds should be ok.
when you call the onclick on span you dont need to use event.preventDefault. but when you use button or a you need to use event.preventDefault. that the basic difference
Why do you need the button element? Just use <span onclick="onClick()> You can style the span with css. Personally I think button is redundant.

Why isn't clear button function isn't working?

The clear button isn't working to clear list-group history
//html
<button class="btn btn-primary mb-3"
type="button"
id="clear-inputs"
onclick="clearIt()">
Clear history
</button>
<form id="history"></form>
<div class="list-group" id="history"></div>
//javascript clear button function
function clearIt() {
document.getElementById('history').value = "";
}
You have two elements with the same id (the <form> and the <div>). Browsers will render this, but it is invalid html, as the id attribute is supposed to be unique to an element. getElementById() is going to grab the first element with the designated id.
The second problem with your html is that neither form or div elements have a value attribute, so there is nothing for your function to clear. It is unclear from your example which element is supposed to be cleared by your button. For the <div>, you could try setting document.getElementById('yourUniqueId').innerHtml = "". That will clear any html inside of the <div>.
You don't need javascript for clear button, you can just use html for clear button only in form tag. Use for clear.
Here is a simple example: example
you have two 'history' id's - not a good practice
use 'innerhtml' instead of value - will yield much better results. value is better for like inputs like a
Make sure you provide a unique ID for your elements,
2 elements above has the same ID, also the function must be defined before calling it.
Always check your Console for logging/errors :)

detect a button click without getElementById

In jupyter, there is a button pointed out by red arrow
Which could be used to summon up a inner command palette
Which is actually an input and a list of <li>
The key function of the button is data-jupyter-action="jupyter-notebook:show-command-palette"
<button class="btn btn-default" title="open the command palette" data-jupyter-action="jupyter-notebook:show-command-palette"><i class="fa-keyboard-o fa"></i></button>
I guess I need a javascript snippet to handle data-jupyter-action attribute.
Usually, script can identify the element by getElementById but this button doesn't have an Id.
How can I detect the button clicking and respond "jupyter-notebook:show-command-palette" action?
You can use querySelector instead of getElementById.
querySelector select elements with css selector.
let elem = document.querySelector('[data-jupyter-action="jupyter-notebook:show-command-palette"]');
This will return the element if it exists. It returns undefined if not found.

javascript, button, click

I have 2 questions, both regarding clicking via js.
So I am on a site and I wish to automate a physical click on 2 buttons, I learned that if we getElementbyId.click() we can do this. But both these buttons do not have an ID. I tried coordinate clicking and it doesn't work and also by the class but to no avail.
<td data-pick="red" class="red" rowspan="2"></td>
How do I click on this?
and also
<button type="submit" class="btn btn-default btn-success">GO</button>
and this.
document.getElementsByClassName doesn't work :(
Give this a try
document.getElementsByClassName('red')[0].click();
Why [0] ? because getElementsByClassName returns classes (matching DOM elements) in form of an array, so [0] is the index here :-)
And for your second button you can trigger the click using
document.querySelector("button[type=submit]").click();
By the way if you are using jquery then why don't you use
$(".red").click();
$("button[type=submit]").click();
Anyways both solutions should work.
Hope that helps :-)
Use jQuery..
$('td[class="red"], button[class="btn btn-default btn-success"]').click();
It is possible to trigger a click using document.getElementsByClassName but you have to understand what you get back from document.getElementsByClassName is not an individual element, but a list which you can iterate over.
You can trigger a click for every item in a collection by doing the following:
var redClassElements = document.getElementsByClassName('red');
for(var i=0;i<redClassElements.length;i++) {
redClassElements[i].click();
}
This will do nothing if you haven't assigned a click handler to the element click() is being called on though.
Also, do you really want to trigger a click on multiple elements? Your best bet is to assign the element an id as has been suggested to you. You can then use document.getElementById('theId').click().

How to make function work after append

For example i'm using append, and for example i'm appendig button in to a div, and i have function $('button_id').click(... etc to work affter i append the div, how can i do that.I mean i get no errors, but the function is not starting, it's because i append and then i want to use the function but how to do that, i tryed with delegate, but same thing.I tryed with function in the button tag , onmouseover and then the function thing, but nothing it gives me function not found.What is the solution ?
I have two events, one event is click event that appends button, the other event is click event that does something if the button that was appended is clicked, but that second event is not working ?
Try using :
$(elem).live(...)
It will bind event for now and in the future.
Firstly, it always helps if you show us the exact source code. $('button_id') is the incorrect selector to start with, try something more along the lines of $('#button_id') as your selector. Also, are you appending dynamic content? Anyways, I've always used the delegate() function quite successfully, but have you tried using the live() function? Also, one more thing to make sure of is that you have the newest version of jQuery as your source.
As was stated as well, you can not have duplicate ids, if you want to have a pointer, use class, instead of id="some_id" use class="appended". To select those using jQuery, use the selector like this $('.appended').
Try something like this it will work as per your expectations.
$("#button_id").click(function(){
//On click code goes here
}).appendTo($("#div_id"));
It's difficult to determine the problem you're having without seeing your code, but delegate (or live) should be perfect for what you're trying to do:
$("body").delegate("#b", "click", function() {
alert("ok");
});
$("#example").append('<input type="button" id="b" value="Click" />');
The click handler above will fire when an element with id="b" is clicked, whether or not that element happens to be in the DOM right now or not.
However, as others have noted, it's important to remember that IDs need to be unique within a document, so by the sounds of it you may be better of using classes instead.
You can see an example of the above code running here.

Categories

Resources