First, I would have created this example in JSFiddle but they are in read-only mode.
I would like to get the specific element that was clicked based on a class.
var button = document.getElementsByClassName("mybutton");
button.onclick = function() {
//how do I reference the specific button that was clicked?
};
<button class="myclass">Button 1</button>
<button class="myclass">Button 2</button>
No jQuery answers please; that is not an option here.
it's not document.getElementByClassName, it's document.getElementsByClassName.
See the difference yet?
It's easy to overlook:
document.getElementByClassName
document.getElementsByClassName
^
The former doesn't exist unless you define it, the latter only works in modern browsers. getElementsByClassName will return a node list, which you need to iterate over to attach event listeners to each node.
var i,
l,
buttons,
button;
function clickHandler(e) {
console.log(this);//the button that was clicked on
}
buttons = document.getElementsByClassName('mybutton');
for (i = 0, l = buttons.length; i < l; i++) {
button = buttons[i];
button.onclick = clickHandler;
}
The first argument in your event handler will be a reference to the event
var button = document.getElementByClassName("mybutton");
button.onclick = function(e) {
//e.Target is a reference to your button
};
Related
i create a lot of listboxes and buttons with javascript.
each button should access a list box. The automatic create in a loop is not a problem. but the click event gives me problems.
normally i would:
var el = document.getElementById ('AButton');
el.onclick = DoFunction;
call this only with automatically created button?
How can I automatically create the DoFunction individually, so that it makes something individual for each button? So is it always the same only with individual controls?
function DoFunction(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
selectbox.remove(i);
}
}
try this:
btn.addEventListener("click", function(){
var btnTwo = document.createElement("BUTTON");
btnTwo.innerHTML = "button";
div.appendChild(btnTwo);
})
<button id="btn">click</button>
<div id="div"></div>
I am a beginner in Javascript.
I'm trying to get the ID of the clicked button.
I have used a function to get the ID, but I am unable to return the value.
How do I return the ID and use it outside?
the alert statement is for testing.
var getID = function(){
var ID=this.id;
alert(ID);
}
document.getElementById('button1').addEventListener('click',getID);
<button id="button1">Click Me!</button>
var getID = function(event){
var ID = event.target.getAttribute('id');
alert(ID);
}
var ID = event.currentTarger.id;
The this keyword refers to the current object that the current function is a part of.
At the base level where there appears to be no object, "document" is the actual object. It is an irrelevance to refer to "this" any further in relation to event handler which could be operating within any object and handling events from beyond the object.
Every event triggered has a number of standard attributes attached to it. "currentTarget" is the element upon which the event listener was triggered calling your event handling function.
So long as the event has an id, the element attribute "id" will tell you what that is.
var getID = function(event){
var elementWithID = event.currentTarget;
var ID = elementWithID.id;
alert(ID);
}
to put it in a more verbose style.
You can get a reference to source clicked element by using e.target.
Here is an simple example.
// get all buttons
const buttons = document.querySelectorAll('button')
// add click event listener to each button
buttons.forEach(button => {
button.addEventListener('click', e => {
console.log(`id -> ${e.target.id}`)
})
})
<button id="hello">Hello</button>
<button id="world">World</button>
<button id="i-am">I'm</button>
<button id="happy">Happy</button>
onclick of a button with a class of obliterate, I want to have my following code take a bunch of identical buttons, besides its unique id and then delete it. The Buttons can be through innerHTML at any time from user input. I want to remove the button onclick, after a confirm This is my current code:
document.getElementsByClassName('obliterate').onclick = function() {
if (confirm('Are you sure you want to delete this?')){
//get this then remove it with remove(this.id);
}
}
Should be straight forward, attach event handler to elements, remove element
var elems = document.querySelectorAll('.obliterate');
for (var i=0; i<elems.length; i++) {
elems[i].addEventListener('click', function() {
if ( confirm('Are you sure you want to delete this?') ) {
this.parentNode.removeChild(this);
}
}, false);
}
If the elements don't exist on pageload, you have to delegate, and doing that without library can be somewhat complicated, depending on what selector you want to match, if there are children inside the clicked element etc. but here's a simlified version
document.addEventListener('click', function(event) {
var clicked = event.target;
var elems = [].slice.call(document.querySelectorAll('.obliterate'));
if ( elems.indexOf(clicked) !== -1 ) {
if ( confirm('Are you sure you want to delete this?') ) {
clicked.parentNode.removeChild(clicked);
}
}
}, false);
FIDDLE
You can use the bind function to provide context so in your case:
element.onclick = function(){ ... }.bind(this);
I have several buttons in my WinJS page.
<button id="btn1">
Button 1
</button>
<button id="btn2"">
button 2
</button>...
and javascript to add click event to clicked button:
(function () {
WinJS.UI.processAll().done(function () {
var showButton = document.querySelector("xxx");
showButton.addEventListener("click", function () {
});
});
})();
How do i determine what button is clicked and set value of "xxx" to id of that button (btn1, btn2 etc...)
If I understood you correctly, you want to identify the button (sender) when you have multiple buttons that are attached to a single event handler.
MSDN:
In JavaScript, Windows Runtime event arguments are represented as a
single event object. In the following example of an event handler
method, the ev parameter is an object that contains both the sender
(the target property) and the other event arguments. The event
arguments are the ones that are documented for each event.
So you need to define an argument for the event handler and use its target property.
Let's say you have the following HTML:
<div id="label1"/>
<div>
<button id="button1">Button1</button><br />
<button id="button2">Button2</button><br />
<button id="button3">Button3</button><br />
</div>
and attached a single event handler to all of the buttons:
var button1 = document.getElementById("button1");
button1.addEventListener("click", buttonClickHandler);
var button2 = document.getElementById("button2");
button2.addEventListener("click", buttonClickHandler);
var button3 = document.getElementById("button3");
button3.addEventListener("click", buttonClickHandler);
you can access to sender in this way:
function buttonClickHandler(eventInfo) {
var clickedButton = eventInfo.target;
var label1 = document.getElementById("label1");
label1.innerHTML = clickedButton.id.toString();
}
Here's a WinJS solution to get the buttons :
var buttons = WinJS.Utilities.query('button');
Then you can bind the event to the buttons click :
buttons.forEach(function (btn) {
btn.addEventListener("click", function () {
console.log('button ' + this.id + ' has been clicked.');
})
});
I am new to WinJS, so there is probably a prettier solution to replace the forEach.
Something like this should work. querySelector only returns the first match, so you need to use querySelectorAll (see docs).
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
var id = this.id;
// do stuff with "id"
});
}
You might also consider looking into jQuery as that can make things like this a little bit cleaner.
I'm binding (or at least trying to) a function for each li element under a ul.
But the event never fires. Take a look at the code below, the alert saying "foo"
is showing, but the next one saying "bar" is supposed to show once a click
on the li tag is invoked.
function set_search_value()
{
var e = document.getElementById("res_ls");
alert("foo");
for (var i = 0; i < e.children.length; i++)
{
e.children[i].onclick = function() {
alert("bar");
}
}
}
HTML
<ul id="res_ls" class="visible">
<li><span><span class="highlighted">test</span>ing.com</span> <span>(181)</span></li>
</ul>
I dropped your exact code into a jsFiddle and it appears to function as desired: http://jsfiddle.net/qVQU4/
I have one piece of advice to offer, though: Attaching individual click handlers to each <li> element can be problematic for performance reasons in long lists, and also requires extra coding gymnastics if items in the list are being manipulated via javascript on the client side. A better technique would be to attach a single event handler to the parent container, and let the click bubble up to that level.
Here's an example using jQuery: http://jsfiddle.net/qVQU4/1/
$("#res_ls").on("click", "li", function(e) {
// e.target will be set to the <li> element that was clicked
alert("bar");
});
Using the latter technique, any new items added to the list will have their clicks handled automatically, without having to wire any additional event handlers.
Look at this example on the jsFiddle:
http://jsfiddle.net/drfisher/Ts7wZ/
var children = document.getElementById("res_ls").children;
var child;
for (var i = 0, len = children.length; i < len; i++) {
child = children[i];
if (child.nodeType == 1) {
child.onclick = function() {
alert(this.textContent);
}
}
}