javascript automatic create button with individuell onclick event - javascript

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>

Related

How to get clicked button that was created dynamically?

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)

Binding listener to a dynamically created element

I am using bootstrap's list group to create a row of tabs. When someone clicks on an element in a table, it dynamically creates a new tab and appends it to that list group.
var newtext = "#"+ticket+" - "+parele.find("td:nth-child(3) strong").html();
var closebtn = $("<button>").addClass("close ml-2 mr-n2 newlyaddedclose").html("×");
var newdiv = $("<div>").addClass("d-flex justify-content-between").append(newtext).append(closebtn);
var newa = $("<a>").addClass("list-group-item list-group-item-action").attr("data-toggle","list").attr("href","#ticket"+ticket).attr("id","ticket"+ticket+"-tab").append(newdiv);
$("#ticketpanel").append(newa);
The problem I am having is the newly created close button. I need to bind a function that identifies when that is clicked to handle closing that tab, but it doesn't seem to be working. In my example here, I added the "newlyaddedclose" class to help identify the new element temporarily and I added the following code below to bind a function that is defined at the top of my script tag:
$(".newlyaddedclose").on("click",".close",closebtn).removeClass("newlyaddedclose");
This still doesn't work. When I inspect the close button element, console shows this error: Framework Event Listeners API Errors:
event listener's handler isn't a function or empt
Am I making this harder than it needs to be, or what am I doing wrong? I can simple put at the end of this element creation this:
$(".close").click(function() { ... });
But doing this starts to double up and triple up etc, those events on already created tabs.
EDIT:
Here is my entire block of script to clear up any confusion.
$(function() {
function closebtn() {
alert("Close button clicked...");
}
$(".ticket-line").click(function() {
var parele = $(this);
var ticket = parele.data("tnum");
// Check to see if ticket is already open in tabs
if($("#ticket"+ticket).length == 0) {
// Create tab on ticket panel
var newtext = "#"+ticket+" - "+parele.find("td:nth-child(3) strong").html();
var closebtn = $("<button>").addClass("close ml-2 mr-n2 newlyaddedclose").html("×");
var newdiv = $("<div>").addClass("d-flex justify-content-between").append(newtext).append(closebtn);
var newa = $("<a>").addClass("list-group-item list-group-item-action").attr("data-toggle","list").attr("href","#ticket"+ticket).attr("id","ticket"+ticket+"-tab").append(newdiv);
$("#ticketpanel").append(newa);
$(".newlyaddedclose").on("click",".close",closebtn).removeClass("newlyaddedclose");
// Create DIV with content
var newdata = $("<div>").addClass("tab-pane").attr("id","ticket"+ticket);
$("#ticket-tabs").append(newdata);
$("#ticket"+ticket+"-tab").tab("show");
} else {
// Ticket is already open, switch to it instead
$("#ticket"+ticket+"-tab").tab("show");
}
});
})
The error is clearly stating you are binding a non function to the event listener. So the error is saying that closeBtn is not a function. Your code, you defined closeBtn as the button you are trying to attach the event too. So change closeBtn in the click event listener to the name of the function you are actually trying to call. If it is the same function name, rename something.
Your problem:
var closeBtn = 1;
if (1===1) {
var closeBtn = 2;
console.log(closeBtn);
}
console.log(closeBtn);
It is unclear why you are selecting the element you just added. You can just attach the event when you create the button, no need to look up the element.
var closebtn = $("<button>")...
closeBtn.on("click", function (){
console.log('clicked', closeBtn);
});
Or use event delegation so any element you add will trigger the function.
$("#ticketpanel").on("click", ".close", function () {
const closeBtn = $(this);
console.log('clicked', closeBtn);
});

How to rebind an event listener to elements that are removed and added again

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>

How to get id of clicked button in winjs

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.

Why is the button disapearing?

The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>
There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>
What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced
remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().

Categories

Resources