Fire event after datatables table finishes rendering - javascript

I am using datatables and fetching the data from an ajax URL. Each row of my returned table data includes a field that renders a button that looks like this:
<button type="button" data-catid="8" data-catname="Programming:JavaScript"></button>
The values assigned data-catid and data-catname come from the datatables retrieved data.
In certain cases, when the table finishes loading, I want to trigger a click on one of these buttons. My code for that is this:
$('#mydatatable').find('button[data-catid="9"]').trigger('click');
However, I cannot find a way to do this so that it occurs after the table has rendered and the button exists in the dom so I can find it and trigger the click.
I have tried drawCallback and initComplete but neither of those is triggered after the button has actually been added to the dom, allowing me to find it with jquery.
Is there a way I can do this? i.e. trigger my click after the mytable has finished retrieving its data via ajax and rendered it?
I am using datatables v 1.10
EDIT:
Here is how my click event handler is attached to the summary table.
var selectedCat = 0;
$('#mydatatable :button').click(function () {
selectedCat = this.getAttribute("data-catId");
console.log("selecteCat is " + selectedCat);
qDetailTable.ajax.url('/datatables/question-data/' + selectedCat).load();
var selectedCatName = this.getAttribute("data-catName");
$('#questDetailCat').text('Questions about: ' + selectedCatName);
$('#questSummary').hide();
$('#questDetail').show();
});

Move the click handler into a separate function, for example:
var selectedCat = 0;
function OnCategoryClick(btn){
selectedCat = btn.getAttribute("data-catId");
console.log("selecteCat is " + selectedCat);
qDetailTable.ajax.url('/datatables/question-data/' + selectedCat).load();
var selectedCatName = btn.getAttribute("data-catName");
$('#questDetailCat').text('Questions about: ' + selectedCatName);
$('#questSummary').hide();
$('#questDetail').show();
});
Event handler needs to be in a named function because you will not be able to trigger click event for elements that are not in DOM as with jQuery DataTables.
Change how you attach your click handler.
$('#mydatatable').on('click', 'button', function () {
OnCategoryClick(this);
});
Remember to always use delegated event handlers with elements inside jQuery DataTables because elements for pages other than first will not be available in DOM. See jQuery DataTables – Why click event handler does not work for more details.
Use $() API method to locate required button and call your handler function OnCategoryClick().
var btn = $('#datatable-summary').DataTable().$('button[data-catid="9"]').get(0);
OnCategoryClick(btn);
Replace datatable-summary with your actual ID of the summary table.
If you need to update details as soon as the summary table is initialized and drawn, use initComplete option to define a callback and do it there.

Related

jQuery Toggling next row in dynamically created table with dynamically created button

I have a jQuery dynamically created table that appends data from json file.
one of the rows of the table is a row of buttons that are appended into a row variable that is appended into the table:
var like = $("<a href='index.html'><button class='likeBtn'>like</button></a>");
var comment = $("<a href='index.html'><button class='comBtn'>comment</button></a>");
var toggle = $("<a href='index.html'><button class='togBtn'>show/hide comments</button></a>");
row3.append(like).buttonset();
row3.append(comment).buttonset();
row3.append(toggle).buttonset();
$("#table").append(row3);
now I need to toggle the row below in the table when clicking the toggle button.
this is my onclick function:
$(function(){
alert("in");
$('.togBtn').click(function() {
alert("in2");
$(this).closest('tr').toggle();
});
});
when I put alerts inside the click function I don't see them, I do see alerts from the function that holds the click function. for example- I see "in" but I don't see "in2".
and of course the row is not toggled.
commentRow is the class of the row that needs to be toggled.
I tried lots of options like-
$("#table").closest('.commentRow').toggle();
also with next() , All(), and many others and I can't get it to work!!!
please - your thoughts on this.
All help will be much appreciated!
It's due to the dynamically generated content, try that:
$(document).on('click','.togBtn',function(e) {
alert("in2");
$(this).closest('tr').toggle();
// or return false; // it does both preventDefault & stopPropagation.
});
This is called event delegation. This technique is only used when you have generated dynamic DOM nodes like as you are doing in your code.
So, in this case all the events were bound when page was initially loaded and the elements are generated after page load, due to that browser didn't registered any event for those elements because of unavailablity. In this case event has to be delegated to the static parent node or to the document itself because it is always available.
Syntax for event delegation using .on() method:
$(staticParent).on(event, selector, cb);
With the help of the answers posted here I found a solution that works:
$(document).on('click','.togBtn',function(e) {
alert("in2");
e.preventDefault();
$(this).parents("tr").next().slideToggle();
// or return false; // it does both preventDefault & stopPropagation.
});
Thanks all for your help!

Changing onclick handler for an element after first click

div.onclick = function(data, dom) {
return function() {
if (data.seenAlready == true) { // HACK
$(this).children().toggle();
return;
}
recursiveSearch(data, dom);
// after this onclick, I want to assign it to a toggle like function. no clue how to do it.
}
}(child, mycontainer.appendChild(div));
I'm trying to swap the onclick method after first onclick on a dom element. I've just not had any success, it seems to some sort of closure loss, or something. I'm fine using jQuery.
You have two ways to do this and both ways are by using a jQuery function:
1) Use one API method - this will work just once. You will click it once and then you choose your own second handler and the first one will not fire again e.g.
$(myselector).one(function(){
$(this).click(myotherhandler);
});
Here is the link to this API http://api.jquery.com/one/.
2) You can choose the following way to replace the event handler .
$(myselector).click(function(){
$(this).off();
$(this).click("secondhandler");
});
this will turn the first handler off and will just fire second handler
Check this jsbin:
http://jsbin.com/fekuq/1/edit?html,js,output

JavaScript disconnect after jQuery replaceWith()

In the application that I'm currently creating, I am doing several AJAX calls to the server and replacing parts of my page with partial views. Everything seems to be working right except for my buttons which are "replaced" using the jQuery replaceWith() function.
In my actual code, I'm replacing a whole <div> not just a button, but the code found here will help illustrated my issue.
When the button is clicked, the JavaScript is called and thusly, that button is then updated. However, try to click on that button again, the same JavaScript will NOT be called or executed. There is some disconnect here that I'm missing. (In my mind, every time that the button with a class of "updateButton" is clicked, the javascript should be executed.) Please help me out.
Thanks
Event delegation.
$(document).on('click','.updateButton',function (e) {
e.preventDefault();
var now = new Date().getTime();
var newButton = "<span class='btn btn-info updateButton'>Update Button " + now + "</span>"
$(this).replaceWith(newButton);
});
Demo: http://jsfiddle.net/D2RLR/896/
Instead of binding the event to the button which will be removed (thus losing the event binding), bind it to an element that doesn't get removed but is an ancestor of that button.
Instead of binding the event handler on the document (as in Kevin B's answer), just re-bind it to the new button you've created to replace the old button with. This is a more efficient method of event handling because the event doesn't need to bubble all the way up the DOM tree to the document before the event fires.
http://jsfiddle.net/D2RLR/900/
var replaceBtn = function(domBtn,e) {
e.preventDefault();
var now = new Date().getTime();
var newButton = $("<span class='btn btn-info updateButton'>Update Button " + now + "</span>");
newButton.on('click',function(event) {
replaceBtn(this,event);
});
$(domBtn).replaceWith(newButton);
}
$('.updateButton').click(function(event) {
replaceBtn(this,event)
});

JQuery ajax and dom issue

I am using JQuery to add a row to a table. Within the row is an element who's click event I am capturing:
$(document).ready(function() {
var newRow = "<tr> ... </tr>";
$('tableName > tbody:last').append(newRow);
$(...).click( function() { // click event on newly inserted elem in the row
alert("click");
});
}
This works great and the alert comes up as expected. BUT when I now add the new row dynamically via an ajax call and parsing the xml, it stops working:
$(document).ready(function() {
getData();
$(...).click( function() { // click event on newly inserted elem in the row
alert("click");
});
function getData() {
$.ajax({
...
success: function(data) {
//parse the xml
$('tableName > tbody:last').append(parsedXml);
}
});
}
The html is correctly added to the DOM, but the click event is no longer captured. Is there some issue with scope or closures going on here?
use
$(...).live('click', function() { // click event on newly inserted elem in the row
alert("click");
});
This keeps the click event running after it has been used
more info
When working with a table, I like to use .delegate() for this. It's very similar to .live(), but lets you set up an event listener on a single parent element, rather than individual handlers on every child element. So whether you have a table of one row or 1000, you still need only one handler.
$('#yourtable').delegate('your_descendant_element','click', function(){
alert("click");
});
You should look into using the live() event handler. It allows you to create an event that matches elements created in the future dynamically, which is what is not happening right now. Another way to fix it would be to move the all to bind down below where you append the new table row, but live() is a much better answer.

preventing effects to be applied to the same object twice when adding objects with ajax

I'm having a little issue with an application I'm making. I have a page where the user edits a document via dragging modules into the page or "canvas" area.
http://thinktankdesign.ca/temp_img.jpg
When the page is loaded, javascript haves the modules collapsible (like above). However after the user drags in a new module the effect is applied again some new modules can collapse as well. here is the problem. each time a module loads the same effect gets applied to the modules that already can collapse. It ends up breaking their animations.
heres the code that gets executed on page load.
//make colapsible
$("h1.handle").click(function() {
var object = $(this);
v$(this).next().toggle("fast", colapsible_class(object));
vreturn false;
}).addClass("open");
and heres the code that gets executed in the creation of a module via ajax
function get_module(id){
var template = $('input[name=template]').val();
$.post(window.location.href, { template: template, module: id, mode: 'create' },
function(data){
$(data).insertBefore(".target_wrapper");
//enable deletion of module
$(".js_no_modules").slideUp("slow");
$(enable_module_deletion());
//show delete button
$("button[name=delete]").show();
//make colapsible
$("h1.handle").click(function() {
var object = $(this);
$(this).next().toggle("fast", colapsible_class(object));
return false;
}).addClass("open");
}
);
}
I need a solid way of preventing the toggle effect to be applied to the same module twice
Use jQuery 1.3 live events instead.
//make colapsible
$("h1.handle").live("click", function() {
var object = $(this);
v$(this).next().toggle("fast", colapsible_class(object));
vreturn false;
}).addClass("open");
and then eliminate the click declaration in the second block of code, changing it to $("h1.handle").addClass("open");
Live events bind all current and future matching elements with an event.
In your Ajax success handler try the following:
//make collapsible
$("h1.handle:not(.open)").click(function() {
var object = $(this);
$(this).next().toggle("fast", colapsible_class(object));
return false;
}).addClass("open");
The best way to solve your problem is, instead of using $("h1.handle") on the AJAX callback, go for $(data).find("h1.handle"). Something like,
var x = $(data);
x.insertBefore(...);
/* your other code */
x.find('h1.handle').click(...).addClass(...);
Like that, only the newly added items will have the event bounded. The already present ones will not be touched.
If we want to answer your question instead of just solving your problem, then we have several alternatives, such as:
store, in your objects, that the onclick event handler has been set so that you don't set it twice
always bind the onclick event, but always unbind it first
use jQuery's live events and the addClass open only on the newly created items.
IMO, the first one is the easiest. You can accomplish it by using jQuery's data(). Then you could do something like:
$("h1.handle").each(function() {
var me = $(this);
// if already has click handler, don't do anything
if (me.data('click_set') != null) { return true; }
// otherwise, store the data and bind the click event
me.data('click_set', true).click(function() {
/* the code you already have on the click handler */
}).addClass('open');
}
The second alternative involves storing the function that you pass inline to the click event binder in a variable, and then using jQuery's unbind to disable it.

Categories