Multiple dynamic onclick buttons triggering multiple times - javascript

I have several buttons that are generated dynamically.
To handle the click events on those buttons I've been using:
$(document).on('click', '.button-class', function() {
// code here
});
The problem is, if the button is dynamically generated again. The click event seems to be bound to the document or something and so clicking that button again will fire the code inside twice. If the button is dynamically generated again it triggers thrice. That's the big issue here because my site is no refresh. So there is instances where content is generated again.
I could use
$(document).unbind('click').on('click', '.delete-order-btn', function() {
//Code
});
Using the unbind, and applying unbind to all my dynamically generated buttons causes them to no longer trigger if they are generated more than once.

Related

How to get xpages modal to fire a close event

I have an xpage (viewed via web browser) which has many <xe:dialog...> controls on it, resulting in bootstrap modal dialogue boxes.
I want to run some client-side script when any dialogue is closed.
So I tried ..
$('.modal').on('hide.bs.modal', function() { ...}
However this didn't work, I suspect because when the xpage is loaded there aren't actually any elements with class 'modal', until one is opened. Then a partial refresh injects the relevant HTML.
So I tried running that line above in the event when the modal opens (in the xpages onShow event), but that didn't fire either. I guess the event might be 'when the modal opens but before it's displayed' meaning the elements aren't ont he screen then either.
So I also tried (hack, hack) a setTimeout of 2 seconds to allow the modal to show first, but still no luck.
So .. question is ..
Using xpages bootstrap modals, via the standard xe:dialog control, how can I attach a client-side javascript event whcih will run when the modal is closed / hidden ?
You can use Event Delegation to bind the listener to a parent element of the (non-existing) modals and trigger a function when a click happens on elements matching the .modal selector in that parent element:
$(document).on("hide.bs.modal", ".modal", function () {...});
I do something similar to this, where a button selection on one modal, closes said modal, and then depending on the button that was clicked, opens the next modal. Instead of doing that, could you not run your script in the same way?
var
currentModal = $(this);
//click next
currentModal.find('.btn-close').click(function(){
currentModal.modal('hide');
OTHER STUFF?
EDIT - My full code:
<script type="text/javascript">
$("div[id^='myModal1']").each(function(){
var
currentModal = $(this);
//click next
currentModal.find('.btn-next').click(function(){
currentModal.modal('hide');
currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal3']").first().modal('show');
});
//click prev
currentModal.find('.btn-prev').click(function(){
currentModal.modal('hide');
currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal2']").first().modal('show');
});
});
$(window).on('load',function(){
$('#myModal1').modal('show');
});
</script>

Is it possible to "steal" an onclick event handler from a button?

Say I have a button that was created dynamically after the DOM was loaded, it's part of a framework code so I can't change it and can't directly access that code.
This button has an on click event with internal state, I want to make another button later that will fire that same function.
If I add the same css classes as the original button to my button it doesn't work, probably because that button's onClick event isn't registered with jQuery but like this:
this.measureToolButton.onClick = function(e) {
self.enableMeasureTool(!self.tool.isActive());
};
So is there another way to "steal" that event from the original?
If you want the new button to perform exactly as if the original button had been pressed, you can just trigger the old button's handler:
$('#newButton').on('click', function() {
$('#oldButton').trigger('click');
});

Adding to innerHTML of document.body causes jQuery .on() to not find its target

So I have some dynamically generated HTML stuff. If you click a button, it adds some html that has another button, and you can add that other html several times, generating several copies of it. This is all inside of a <form> tag, so I need to use e.preventDefault() on each button to prevent javascript from trying to submit the data. Each button also has its own code for onclick. There's a problem with javascript-added click events on newly generated content however. If I have <button class="myBtn"></button>, then in javascript I have $(".myBtn").click(...), that will work just fine, but only for buttons that already exist when the javascript code is run, meaning newly generated buttons won't have the event attached. The solution to that problem is found here.
Now we come to the real issue. That all works perfectly, but only until I add to document.body.innerHTML. As soon as I execute the line document.body.innerHTML += "Text", the code from the link above no longer executes when the generated button is clicked.
I have an example here: https://jsfiddle.net/6hvgatLy/1/
You are re-writing the whole body innerHTML which will remove all event listeners
Use append() instead
Change
$("#deadlyBtn").click(function(e){
e.preventDefault();
document.body.innerHTML += "Now try clicking [Add new Input]"
})
To
$("#deadlyBtn").click(function(e){
e.preventDefault();
$('body').append("Now try clicking [Add new Input]")
})
DEMO
Alternatively you can change your event delegation to an asset that isn't being overwritten like body or document
$(document).on("click", ".formDiv .innerContainer .innerBtn", function(e){
e.preventDefault()
$(this).before($('<input type="text" placeholder="Textbox"/>'))
})

How to bind an event within dynamically loaded content on a click event?

I have a div inside my html with the id pageContent. When users click various buttons, it will load the appropriate content. When a user clicks the javaQuestions button it loads, javaQuestions.html into the div just fine. However, inside, the javaQuestions.html, I have a collapsible list, and I can't figure out a way to "bind" the li collapse/uncollapse without having the user to click TWICE. Right now what I have is:
$("#pageContent").on('click', 'li', function (){
$('.collapsible').collapsible();
});
So I guess what happens is, first the user clicks on the button, and it loads content. Then, the user clicks on any li, and it enables the "collapsible()" function, but does not uncollapse/collapse the content. Only when the user clicks a second time does it works fine. I tried adding the line $('.collapsible').collapsible(); into the event that loads the javaQuestions.html content, but it doesn't do anything. Kind of at a roadblock, any ideas?
EDIT: Here is the code that loads the content:
$("#pageContent").on('click', '#javaQuestions', function (e) {
fadeIn("#pageContent", "../java-questions/javaQuestions.html", 50);
fadeIn("#commentsContent", "../comments/comment-section.html", 500);
});
I also really want to know how this will function once I figure it out. But as you can see, the above function loads the javaquestions.html, and I can't seem to find a way to ALSO bind 'li' to be collapsible in one swoop.
Have you tried using jQuery bind method? You can bind your handler to, say, body and then you don't have to care about loading and attaching a handler after it.
Update: may be this will help:
$(document).ready(function() {
$("body").on('click', '#pageContent li', function (){
$('.collapsible').collapsible();
});
});
Use this DOCUMENT because it is dynamically loaded
$(document).on("click","li #pageContent",function(){
$('.collapsible').collapsible();
});

Dynamically Created Check Box in Header of Jquery UI Accordion

I am creating an accordion from a DB with checkboxes in the headers. I have seen the solutions that solve the problem of clicking the checkbox without activating the accordion using the click() function, but since I am dynamically creating the accordion, the click() function will not work. I am at a loss as how to solve the problem of clicking a checkbox in a dynamically generated accordion header.
The problem is that the click event activates the accordion before the on('click') has a chance to run e.stopPropagation.
Any Ideas?
The problem is when you use event propagation to register the event handlers, it is normally attached to the body or some elements which is much higher up in the hierarchy. So by the time the events attached to accordion headers will be executed resulting in collapsing/expanding the tab.
Since you are creating the checkbox dynamically, the solution is to add the click event handler preventing propagation to the checkbox after it is created.
Ex:
var chk = $('<input />', { type: 'checkbox'});
chk.click(function(e){
e.stopPropagation();
});
chk.appendTo(accordionHeader)

Categories