misbehave javascript when the associate class has multiple instance - javascript

The Js snippet below work for single html table (class = mtable), basically it will freeze the first column when i scroll left on the table. it misbehave when i have multiple "mtable" class html table where scroll at one table will cause all the table scroll at the same time. How should i fix this so that each table will work independently?
$(document).on('mouseover', '.mtable tbody', function(){
// alert('scrolling');
$('.mtable tbody').on('scroll', function() {
$('.mtable thead').css("left", -$(".mtable tbody").scrollLeft());
$('.mtable thead tr th:first-child').css("left", $(".mtable tbody").scrollLeft()-2);
$('.mtable tbody tr td:first-child').css("left", $(".mtable tbody").scrollLeft()-2);
});
});

You need to store a reference to the current .mtable element and then call the DOM traversal functions based on that table only, something like this:
$(document).on('mouseover', '.mtable tbody', function() {
var $tbody = $(this);
var $table = $tbody.closest('.mtable');
var $thead = $table.find('thead');
var $tbody = $table.find('tbody').off('scroll').on('scroll', function() {
$thead.css("left", -$tbody.scrollLeft());
$thead.find('tr th:first-child').css("left", $tbody.scrollLeft() - 2);
$tbody.find('tr td:first-child').css("left", $tbody.scrollLeft() - 2);
});
});

Related

Removing class of singular row in a table

When I click a row in a HTML table, I want to remove the highlightedRow class from the previously clicked row, and add it to the new one.
$(function () {
$("table tr").click(function (e) {
//remove class
var dataTable = $("#TemplateData");
dataTable.removeClass("highlightedRow");
//add class
var dTable = $(this);
dTable.addClass("highlightedRow");
g_previouslyClickedRow = $(this).index()
}
Problem is:
var dTable = $(this);
dTable.addClass("highlightedRow");
is getting the row element while:
var dataTable = $("#TemplateData");
dataTable.removeClass("highlightedRow");
is getting the table element.
How can I use the table element and the previouslySelectedRow value?
g_previouslyClickedRow = $(this).index()
to get the row element?
You need to target proper element to removeClass
$("table tr").click(function (e) {
//remove class
$('.highlightedRow').removeClass('highlightedRow');
//add class
$(this).addClass("highlightedRow");
}
When you say :
var dataTable = $("#TemplateData");
//dataTable will have reference to your table if #TemplateData is the id of your table
dataTable.removeClass("highlightedRow");
//the above line will just remove class from table as you have stored reference of your table
//in dataTable
and when you say:
var dTable = $(this);
//$(this) will be referring to current element context inside click
dTable.addClass("highlightedRow");
//and thus the clicked element, whose reference is stored in dTable, will get the class
//highlightedRow.
Do Simply
$(".highlightedRow").removeClass("highlightedRow");
$("table tr").click(function (e) {
g_previouslyClickedRow = $('.highlightedRow').index();
//remove class
$('.highlightedRow').removeClass("highlightedRow");
//add class
$(this).addClass("highlightedRow");
}

creating a 2 column table dynamically using jquery

I am trying to generate a table dynamically using ajax call. To simplify things i have just added my code to js fiddle here -> http://jsfiddle.net/5yLrE/81/
As you click on the button "HI" first two columns are created properly.. but some how as the td length reaches 2 . its not creating another row. The reason is that when i do find on the table elements its actually retrieving the children table elements. Can some one pls help.
I want a two column table.. Thank you.
sample code:
var tr = $("#maintable tbody tr:first");
if(!tr.length || tr.find("td:first").length >= max) {
$("#maintable").append("<tr>");
}
if(count==0) {
$("#maintable tr:last").append("<td>hi"+content+"</td>");
}
Basically the matching of descendants was allowing for great great grandchildren etc. Just needed to make the matching more specific.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5yLrE/91/
max = 2
$("button").click(function () {
var content = $('#template').html();
var $table = $("#maintable");
var tr = $table.find(">tbody>tr:last");
if (!tr.length || tr.find(">td").length >= max) {
// Append a blank row
tr = $("<tr>");
$table.append(tr);
}
tr.append("<td>hi " + content + "</td>");
});
This one always targets the last row and adds a row if it does not exists at all (or there are too many divs already) which is what I gather you intended.
I also used the templating I suggested to separate messy HTML strings from the code.
You will want to check the length of the table cells before incrementing a new table row. After you have reached your max column length, reset the row and start over.
JSFiddle
max_columns = 2;
count=0;
$("button").click(function() {
var content='column';
if(count==max_columns||!$('#maintable tr').length){
$("#maintable").append("<tr>");
count=0;
}
if(count!=max_columns)
$("#maintable tr:last").append("<td>"+content+"</td>");
else
$("#maintable tr:first").append("<td>"+content+"</td>");
count++;
});

How can I bind a click event to dynamically created TDs?

I have a function that takes some json data and puts it into a table. I'm trying to bind a click event to certain table elements. In this case the table has two columns 'Drink Name' and 'Drink Type'. I want the two columns to have different events so I'm trying to give them class tags so I can bind the event to a given class.
The lines wrapped in ** are pseudo code for what I'm trying to do. I've tried looking at a bunch of stuff and can't quite figure this out...thanks!!
function totable(data){
var d = document.getElementById("drinkList");
d.setAttribute("class","panel panel-default");
var dd = document.createElement("div");
dd.setAttribute("class","panel-heading");
dd.appendChild(document.createTextNode("Drink list"));
d.appendChild(dd);
var mytable = document.createElement("table");
mytable.setAttribute("class","table");
var thr = document.createElement("tr");
for(var key in data[0]){
var th = document.createElement("th");
th.appendChild(document.createTextNode(key));
thr.appendChild(th);
}
mytable.appendChild(thr);
for(var i=0;i<data.length;i++){
var r = document.createElement("tr");
for(var key in data[i]){
var td = document.createElement("td");
**td.setClassName("drinkEntry");**
td.appendChild(document.createTextNode(data[i][key]));
r.appendChild(td);
}
mytable.appendChild(r);
}
d.appendChild(mytable);
**$("#drinkEntry").on("click", viewDrink);**
}
Replace **td.setClassName("drinkEntry");** with $(td).click(viewDrink);.
you can use method .on() with document to bind the event instead directly to the class (not id) because the instance doesn't exist already
try this:
$(document).on("click",".drinkEntry", function(){
});
Try this
$('body').on('click','#drinkEntry',function(){
//Your Codes
});
To bind event to dynamically created items you must use .on() jQuery function.
In your case it should looks like:
$('#drinkEntry').on("click", function () {
//logic
});
try out
$('body').on('click', 'td.drinkEntry', function() {
alert("td clicked");
});
JsFiddler Demo
you can also read help full aticle for this : Bind events to dynamically created elements using jQuery

Use Javascript to scroll in HTML tables?

I have a few table in a scrollbox. Upon loading the page I would like it to automatically scroll to the first empty table row using Javascript. Is this possible?
$("table tr").each(function() {
var cell = $.trim($(this).find('td').text());
if (cell.length == 0){
var el = cell;
el.scrollIntoView(true);
}
Once you have the empty row, you can scroll to it like this.
function scrollIntoView(el){
window.scrollTop( el.offset().top - ($(window).height()/2) );
}

jQuery: slideDown undesirably instant with no animation

I've written a short method to append rows to a table. It is as follows:
/*--------------------------------------------------*/
/* Append a row to the documentation heading table. */
/*--------------------------------------------------*/
function append_heading(heading, style, default_content, node_enabled, leaf_enabled)
{
// Grab the table body.
var tbody = $("#headings_table_body");
// Generate our cells.
var headingCell = $('<td class="heading_column"></td>');
var styleCell = $('<td class="style_column"></td>');
var defaultCell = $('<td class="default_column"></td>');
var nodesCell = $('<td class="nodes_column ticked"></td>');
var leavesCell = $('<td class="leaves_column ticked"></td>');
// Fill in various cells.
headingCell.append(heading);
styleCell.append(style);
defaultCell.append(default_content);
// Tick some cells cross the others.
if(node_enabled)
{
nodesCell.addClass("ticked");
}
else
{
nodesCell.addClass("crossed");
}
if(leaf_enabled)
{
leavesCell.addClass("ticked");
}
else
{
leavesCell.addClass("crossed");
}
// Add all the cells to one big row.
var tr = $("<tr></tr>")
.append(headingCell)
.append(styleCell)
.append(defaultCell)
.append(nodesCell)
.append(leavesCell);
// Append the row to the table.
tbody.append(tr);
$(tr).hide();
$(tr).slideDown("slow");
}
It appends the rows as expected, all nicely filled out and styled. The problem is, slideDown doesn't animate: It's current behaviour is analogous to me calling hide() and show(), it simply appears. How can I get this to animate correctly? Any help is appreciated, thanks.
jQuery is NOT able to animate tables directly. All that you need is to wrap the content of each td cell in the row into div with display:none and make slideDown animation for them! To make you life easier :)))
tr.find('td').wrapInner('<div style="display: none;" />');
tr.appendTo(tbody);
tr.find('td > div')
.slideDown('slow', function(){
var $set = $(this);
$set.replaceWith($set.contents());
});
If you want to animate the whole table, it should be placed into div with animation applied to that div.
I assume it's because it does not know the height of the appended TR, try explicitly defining the height of the TR in your CSS or amend the code to do
$(tr).height($(tr).height());
$(tr).hide();
$(tr).slideDown("slow");

Categories