How to reattach event bindings after DOM is completely changed [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I am working on a C# Razor site and I am POSTing from a boostrap modal which then returns a new view and model. To reload the entire page with the response, I am using the following line within this code block.
$("html").html(response);
function addDevice(e) {
e.preventDefault();
var ID = $("#txtNewDeviceID").val();
var Name = $("#txtNewDeviceName").val();
$.post('#Url.Action("AddDevice", "Devices")', { 'DeviceID': ID, 'DeviceName': Name }, function (response) {
$('#newDeviceModal').modal('hide');
$("html").html(response);
AttachBindings();
});
}
Here is the code behind AttachBindings():
function AttachBindings() {
$(document).on('click', 'table tr', {}, tableClick);
$(document).on('keyup', '#search', {}, search);
$(document).on('click', '#btnAdd', {}, function (e) {
addDevice(e);
});
$(document).on('click', '#btnRemove', {}, function (e) {
removeDevice(e);
});
$(document).on('click', '#btnUpdate', {}, function (e) {
updateDevice(e);
});
}
Unfortunately AttachBindings() is never hit and I can't seem to find a way to reattach these events. The only event that seems to work is keyup which is attached to #search. Any ideas on how to fix this?

Try using live function and call it on document.ready
As per the details provided in the documentation for LIVE:
Description: Attach an event handler for all elements which match the
current selector, now and in the future.
Hence, even if an element is added later in the DOM, the event will be triggered by that element
Whereas, in the case of ON, it will be added to the present elements only:
Description: Attach an event handler function for one or more events
to the selected elements.
So, calling it once, after document is ready and bind the events using bind or live will do the magic for you.

I doubled checked this morning and the events are being hit the way I have it. The real issue is the bootstrap modal that I have on the page does not work if the DOM has been updated. It looks like I will need to reconnect the data-toggle and data-dismiss events. I'm guessing bootstrap does this in the background when the page first loads.
Also the .Live method is deprecated according to the JQuery documentation.
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event >handlers. Users of older versions of jQuery should use .delegate() in preference >to .live().
Also AttachBindings does not need to be called more than once. My code updated looks like this now:
function addDevice(e) {
e.preventDefault();
var ID = $("#txtNewDeviceID").val();
var Name = $("#txtNewDeviceName").val();
$.post('#Url.Action("AddDevice", "Devices")', { 'DeviceID': ID, 'DeviceName': Name }, function (response) {
$('#newDeviceModal').modal('hide');
$("html").html(response);
});
}

Related

Is there an alternative to JQuery`s event delegation?

I want to be able to assign a function to keypress of elements that don't exist when the DOM loads. In jQuery the code I had is like this
$(document).on('keypress', '.sc-chat-window .sc-user-input--text, #waste-form input,#address,.waste-wise-container .form-control,.widget-box .form-control,#aria-main-search-form-field,#footer-search-field,#aria-feedback-form-field', function(e) {
updateLastTypedTime();
});
It worked fine, but the problem is I can't use jQuery anymore and I would like to use Pure JavaScript this is what I have. The issue is that some elements don't exist yet so when this runs, it doesn't add the eventListener to the selectors.
JS:
var keyPressElements = document.querySelectorAll('form[id="4840400"],#waste-form input,#address,#aria-main-search-form-field,#footer-search-field,#aria-feedback-form-field');
keyPressElements.forEach(function(elem) {
elem.addEventListener('keypress', function() {
updateLastTypedTime();
});
});
How can I fix this issue?

Jquery replaceWith() inside loop with click events

im trying to replace various elements with another inside a jquery .each loop and give them on click events to their child nodes, but it does not work, here is my code.
var replacer = function () {
var elementbody = "<div class='Container'><div class='Button'></div></div>";
$('.myclass').each(function (index, element) {
$(element).replaceWith(elementBody);
$(element).find('.Button').click(function () {
//------------------To do on click event------------------//
});
};
After you use
$(element).replaceWith(...);
element still refers to the old element, not the elements that have replaced it. So $(element).find('.Button') doesn't find the button you just added.
Instead of adding the handler to each element that you add, use delegation to bind a handler just once, as explained in Event binding on dynamically created elements?
$("someSelector").on("click", ".Button", function() {
...
});
You can use a delegate as Barmar suggests or you could provide yourself with a new jquery object that references your new content before running the replaceWith
Something like this, maybe:
new_element = $('<div><button>Hello World</button></div');
$(element).replaceWith(new_element);
new_element.find('button').on('click', function(e) {
console.log(e);
});

Binding a click event in my JavaScript module

Since I started structuring my JavaScript as a module pattern, some of my click events no longer work. Since other parts of my JavaScript add HTML to the DOM, I need to use $('body').on('click') for a button.
This is what my module currently looks like:
var s,
MyApp = {
settings: {
fooButton: $(".foo-button"),
barButton: $(".bar-button")
},
init: function() {
s = this.settings;
this.bindEvents();
},
bindEvents: function() {
// this works
s.fooButton.on("click", function() {
MyApp.clickButton("foo");
});
// this does NOT work
$('body').on('click', s.barButton, function (event) {
MyApp.clickButton("bar");
});
},
clickButton: function(button) {
console.log("You clicked " + button)
}
};
The first click event is working, the second isn't. How can I bind and event for an element that was created by JavaScript code?
The second argument for your handler when the event is delegated is expected to be a string.
In your case it is a jQuery Object.
That is the root cause your click event is not working.
Change
barButton: $(".bar-button")
to
barButton: ".bar-button"
If you're creating the element in JS, you have to bind the event AFTER the element is created.
So put the binding event in a function, then call that function after your JS code has created the element. :)
When using .on() for event delegation, the second parameter has to be a string. Passing anything else won't work.
http://api.jquery.com/on/#on-events-selector-data

event listner not working for appended items

hey all i am appending a form to a page on click the form has some text boxes and i need to add event listner like on keypress but the function dosent works dont know where is the problem the function works well everywhere but not for this form here is the code.
appending the form
function activityCHART(thisobj){
var theidis=$(thisobj).attr("id");
$("#FULL_FADE").fadeIn();
$.ajax({
type: 'post',
url: 'newpage.php',
data:{'actde':theidis},
success: function(dataa){
$("#the_APPEDEDr5").empty().append(dataa);
}});}
newpage this textbox is present and some more text areas
<input type="text" name="deptname" placeholder="department name" id="detp_names09o" class="TEXTNAME_o909ioi"/>
add this event listner
$('#detp_names09o').keypress(function (e) {
alert('ok');});
these are some script links
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
i think there are some script link problem
alert comes when i does it like this onkeyup="thisisfun();" function thisisfun(){ alert('ok'); }
You should use live(), delegate() or on() to attach event listeners to dynamically added DOM elements. bind() and keypress() doesn't work for elements that are dynamically added to DOM[see this]
$('#detp_names09o').live("keypress",function (e) {
//do some stuff
});
.on() is mostly syntax sugar that can mimic .live(), or .delegate() depending on how you call it.
$('#detp_names09o').on("keypress",function (e) {
//do some stuff
});
Also, you have specified two different versions of jQuery. Though CDN's do have some advantages over locally referenced libraries, they might break your code at-times.
If thats the reason you've referenced to local jQuery file(along with CDN version), you might consider looking at CDN fallbacks. In either case, you should be careful about the version you are using.
Cheers!
To attach event to dynamically added elements,
Try binding the event using 'bind'
$('#detp_names09o').bind("keypress",function (e) {
alert('ok');
});
or use 'on'
$('#detp_names09o').on("keypress",function (e) {
alert('ok');
});
Also you dont require two versions of jquery in your page, also make sure this id is not duplicated
use onkeyup,.. attribute inside the element and call the function like this
<input type="text" name="deptname" placeholder="department name" id="detp_names09o" class="TEXTNAME_o909ioi" onkeyup="functionName()"/>
in javascript
function functionName(){
//your code
}
First of all you should decide what do u want to use, keyup or keypress ? For example if you want to use keyup and you are using jquery version greater than 1.7 then use
$(document).ready(function () {
$('#element').on("keyup",function () {
alert('result ok');
});
});
else u can use
$(document).ready(function () {
$('#element').live('keyup', function() {
alert('result ok');
});
});
Make sure that you are calling working script (check your script link), try not to make duplicate ids of elements instead use class and avoid using inline use of javascript. Happy Coding !

JQuery/Javascript - What exactly is the valueCommit event, at what point is it called?

I've come across this in JQuery:
$("#myHTMLcontrolID").bind('valueCommit', function (e, combo) {
//function code here
});
It's being used to bind a dropdown so that when an option is selected in the dropdown, Ajax is used to update a linked dropdown.
My question is, would someone please clarify what this event is (like is it a JQuery or AJAX specific event), and what are the immediately preceding and succeeding JavaScript events (e.g. like OnChange)
It's a custom JQuery event that just happens to be the name of an Adobe flex built-in event. See http://www.sitepoint.com/jquery-custom-events/ for an explanation of how to create a custom JQuery event
I found the usage of the event in this code in the solution:
$('select').sexyCombo({
hideListCallback: function () {
$(this).trigger('valueCommit');
},
initEventsCallback: function () {
$(this).bind('valueCommit', { that: this }, function (e) {
var combo = e.data.that;
var selectElement = combo.selectbox;
$(selectElement).trigger('valueCommit', combo);
})
}
});
As to when a JQuery custom event is called in relation to, for example 'onChange', I still don't know

Categories