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.
Related
I am trying to get a dynamically created button in order to access its parent.
I already tried to do:
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click(this)", add);
sadly the button won't work if i type "click(this)". It only works if I type "click".
Changing the method to function add(element) from function add() also did not work.
How can i access the parent of my clicked button?
I cant create my buttons in HTML since i am creating a dynamic list of buttons which may differ depending on the size of the array.
Also my code should only be in Javascript
Thanks for the help!
By magic, I mean by the standard, the button reference is passed to the object.
function add() {
console.log(this);
}
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click", add);
<div id="addButton"></div>
If you really wanted to pass along a variable
function add(btn, what) {
console.log(btn, what);
}
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click", function(){ add(this,'foo'); });
<div id="addButton"></div>
Check this : https://www.w3schools.com/jsref/met_document_addeventlistener.asp
You should use btn.addEventListener("click", () => {}) instead of btn.addEventListener("click", () => {}).
But I think it would be better to use document.addEventListener((e) => {}) and then check the target (e.target)
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>
I have built a pretty complex slider and now have to build it so it can be removed and re-added to the page based on a selection. I have a simple click event listener for the pagination to call all my animations and timers that looks like this
let $slideItems = $slideShow.querySelector('.slideshow-items'),
$slideshowNav = $slideShow.querySelector('.slideshow-nav'),
$slideshowNavButton = $slideshowNav.getElementsByTagName('button');
forEach($slideshowNavButton, (index, el) => {
el.addEventListener('click', function() {
let isActive = this.classList.contains('active');
if (!isActive) {
clearTimeout(timer);
slideshowClick($slideShow, this);
slideshowAnimations($slideShow, index);
slideTimer();
}
});
});
I use the forEach function as a for loop to go through all the elements I need, like having multiple $slideShow's on the page, and return them as an indexed array. The issue I am having is that I need to add a functionality in which the $slideshowNav and all the $slideshowNavButtons get removed and rebuilt from a function outside of the $slideshow function and can't figure out how to rebind the click event without repeating all of the code. Is there a way to bind this event to the $slideshow object, similar to the way jQuery's .on function works or rebind the click event to the new $slideshowNavButton's after they are created? I am not able to use jQuery so I can't use the .on function.
its hard to give you correct answer since you motion too many classes without visual placement but hope this helps:
var btnWraper = document.querySelectorAll('.btnWraper > button');
btnWraper.forEach(function(e){
e.onclick = buttonClicking;;
})
let remake = document.getElementById('reMakeMe');
remake.addEventListener('click', function(){
var btnWraper = document.querySelectorAll('.btnWraper > button');
//if deleted
if(!btnWraper.length)
{
createButtons('Btn1');
createButtons('Btn2');
createButtons('Btn3');
createButtons('Btn4');
}
},false)
let rest = document.getElementById('resetMe');
rest.addEventListener('click', function(){
var btnWraper = document.querySelectorAll('.btnWraper > button');
btnWraper.forEach(function(e){
e.remove();
})
},false) ;
function buttonClicking (){
alert(this.innerHTML);
}
function createButtons(value){
var btn = document.createElement("button");
btn.innerHTML = value;
btn.onclick = buttonClicking;
var parentElement = document.getElementsByClassName("btnWraper")[0];
parentElement.appendChild(btn);
}
<div class="btnWraper">
<button>Btn1</button>
<button>Btn2</button>
<button>Btn3</button>
<button>Btn4</button>
</div>
<div>
<button id="resetMe">Reset All</button>
<button id="reMakeMe">ReMake All</button>
</div>
I have a button appended to a parent button:
var parent_button = document.createElement("button");
var child_button = document.createElement("button");
parent_button.appendChild(child_button);
I want to create functionality for the child_button that's independent from that of the parent_button:
parent_button.onclick = function () {
//do stuff
};
child_button.onclick = function () {
//do some other stuff
};
But given this code, whenever I click on child_button, I am necessarily triggering parent_button.onclick(). How do I separate the two?
The overlapping buttons look like this:
Use stopPropagation() on the event object of the child button. It will prevent the event from propagating from the child to the parent.
You can see an example here:
var pb = document.getElementById("pb");
var cb = document.getElementById("cb");
pb.addEventListener("click", function(e) {
console.log("Parent");
});
cb.addEventListener("click", function(e) {
console.log("Child");
e.stopPropagation();
})
<button id="pb">Parent Button <button id="cb">Child Button</button></button>
Note: I think that the default behavior is that when you click on a child element, the event of both the child and the parent should trigger, but in this example, this doesn't happen; maybe it's something particular to buttons being parents.