bootstrap "tooltip" and "popover" add extra size in table - javascript

Note:
Depending on you Bootstrap version (prior to 3.3 or not), you may need a different answer.
Pay attention to the notes.
When I activate tooltips (hover over the cell) or popovers in this code, size of table is increasing. How can I avoid this?
Here emptyRow - function to generate tr with 100
<html>
<head>
<title></title>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script type="text/javascript" language="javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.2.1/bootstrap.min.js"></script>
<style>
#matrix td {
width: 10px;
height: 10px;
border: 1px solid gray;
padding: 0px;
}
</style>
<script>
function emptyRow() {
str = '<tr>'
for (j = 0; j < 100; j++) {
str += '<td rel="tooltip" data-original-title="text"></td>'
}
str += '</tr>'
return str
}
$(document).ready(function () {
$("#matrix tr:last").after(emptyRow())
$("[rel=tooltip]").tooltip();
});
</script>
</head>
<body style="margin-top: 40px;">
<table id="matrix">
<tr>
</tr>
</table>
</body>
</html>
thank in advice!

Note: Solution for Bootstrap 3.3+
Simple Solution
In the .tooltip() call, set the container option to body:
$(function () {
$('[data-toggle="tooltip"]').tooltip({
container : 'body'
});
});
Alternatively you can do the same by using the data-container attribute:
<p data-toggle="tooltip" data-placement="left" data-container="body" title="hi">some text</p>
Why does this work?
This solves the problem because by default, the tooltip has display: block and the element is inserted in the place it was called from. Due to the display: block, it affects the page flow in some cases, i.e pushing other elements down.
By setting the container to the body element, the tooltip is appended to the body instead of where it was called from, so it doesn't affect other elements because there is nothing to "push down".
Bootstrap Tooltips Documentation

Note: Solution for Bootstrap 3.0 ~ 3.2
You need to create an element inside a td and apply a tooltip to it, like this, because a tooltip itself is a div, and when it is placed after a td element it brakes table layout.
This problem was introduced with the latest release of Bootstrap. There are ongoing discussions about fixes on GitHub here. Hopefully the next version includes the fixed files.

Note: Solution for Bootstrap 3.3+
If you want to avoid to break the table when applying a tooltip to a <td> element, you could use the following code:
$(function () {
$("body").tooltip({
selector: '[data-toggle="tooltip"]',
container: 'body'
});
})
You html could look like this:
<td data-toggle="tooltip" title="Your tooltip data">
Table Cell Content
</td>
This even works with dynamically loaded content. For example in use with datatables

I would like to add some precision to the accepted answer, I decided to use the answer format for readibility.
Note: Solution for Bootstrap 3.0 ~ 3.2
Right now, wrapping your tooltip in a div is the solution, but it will need some modifications if you want your whole <td> to show the tooltip (because of Bootstrap CSS). A simple way to do it is to transfert <td>'s padding to wrapper :
HTML
<table class="table table-hover table-bordered table-striped">
<tr>
<td>
<div class="show-tooltip" title="Tooltip content">Cell content</div>
</td>
</tr>
</table>
JS (jQuery)
$('.show-tooltip').each(function(e) {
var p = $(this).parent();
if(p.is('td')) {
/* if your tooltip is on a <td>, transfer <td>'s padding to wrapper */
$(this).css('padding', p.css('padding'));
p.css('padding', '0 0');
}
$(this).tooltip({
toggle: 'toolip',
placement: 'bottom'
});
});

If you are using datatable for table then it will be use full
$('#TableId').DataTable({
"drawCallback": function (settings) {
debugger;
$('[data-toggle="tooltip"]').tooltip({
container: 'body'
});
}
});

You should initialize Tooltip inside datatable function fnDrawCallback
"fnDrawCallback": function (data, type, full, meta) {
$('[data-toggle="tooltip"]').tooltip({ placement: 'right', title: 'heyo', container: 'body', html: true });
},
And define your column as below
{
targets: 2,
'render': function (data, type, full, meta) {
var htmlBuilder = "<b>" + data + "</b><hr/><p>Description: <br/>" + full["longDescrioption"] + "</p>";
return "<a href='#' class='Name'>" + (data.length > 50 ? data.substr(0, 50) + '…' : data) + "</a>" +
"<sup data-toggle='tooltip' data-original-title=" + htmlBuilder + ">"+
"<i class='ic-open-in-new ic' style='font-size:12px;margintop:-3px;'></i></sup>";
}
},

If you're using bootstrap directives for AngularJS, use tooltip-append-to-body attribute.
<td ng-repeat="column in row.columns" uib-tooltip="{{ ctrl.viewModel.leanings.tooltip }}" tooltip-append-to-body="true"></td>

Related

detecting class changes in Bootstrap Switch Jquery (converting working checkbox JS to button js)

I am trying to convert a piece of JQuery that changes the class of a tr when checked to a piece of JQuery that changes the class of a tr when a button gets a class called "active". I am a JQuery/Javascript newbie and I am at a loss.
For those who have suggested it's a duplicate, I have tried to detect class and failed (updated code below).
ORIGINAL CODE (THAT WORKS)
javascript:
var $input_class = $('.addCheckbox');
function setClass() {
var tr = $(this).closest( "tr" );
if ($(this).prop('checked') == true){
tr.addClass( "highlight" );
}
else{
tr.removeClass( "highlight" );
}
}
for(var i=0; i<$input_class.length; i++) {
$input_class[i].onclick = setClass;
}
MY HORRIBLE TRY (UPDATED BELOW...NO LONGER THIS)
javascript:
var $input_class = $('.btn-group .btn-toggle .btn');
function setClass() {
var tr = $(this).closest( "tr" );
if ($(this).prop('.btn-success .active')){
tr.addClass( "highlight" );
}
else{
tr.removeClass( "highlight" );
}
}
for(var i=0; i<$input_class.length; i++) {
$input_class[i].onclick = setClass;
}
I am using the Bootstrap Switch Plugin which converts checkboxes to toggles
http://www.bootstrap-switch.org/
The converted html looks like this:
<tr>
<td width="15px"><input class="addCheckbox" type="checkbox" value="true" style="display: none;">
<div class="btn-group btn-toggle" style="white-space: nowrap;">
<button class="btn active btn-success btn-md" style="float: none; display: inline-block; margin-right: 0px;">YES</button>
<button class="btn btn-default btn-md" style="float: none; display: inline-block; margin-left: 0px;"> </button>
</div>
</td>
<td width="85px">May 2016</td><td class="restaurant-name">
Joe's Crab Shack
</td>
<td class="text-center">
#my table info
</td>
</tr>
UPDATE!!! As per 'duplicate' suggestions.
After looking through this question (which was very helpful), I have changed my code to this, and I still can't get it to work. I am wondering if it is having trouble finding the exact input class? Because the plugin converts the checkbox to html, I can't (or don't know how) set specific names or ids for the buttons.
javascript:
var $input_class = $('.btn');
var tr = $(this).closest( "tr" );
function checkForChanges()
{
if ($('.btn').hasClass('btn-success'))
tr.addClass( "highlight" );
else
tr.removeClass( "highlight" );
}
for(var i=0; i<$input_class.length; i++) {
$input_class[i].onclick = checkForChanges;
}
There are issues in your code resulting from not being familiar with the language. Also keep in mind this jQuery what you posted, not javascript.
As I am not quite sure what is your final objective here so let's go step by step.
First of all:
$('.btn-group .btn-toggle .btn');
The above means an element with all three classes class="btn-group btn-toggle btn" and I do not see such in your code. Are you sure you didn't want to use $('.btn-group, .btn-toggle, .btn'); ? At the moment var $input_class is empty, so later in your code you loop through nothing.
Second thing:
as I posted in the comments make sure you run your script after loading jQuery and rest of the content of the page. If your script is above jQuery, like this:
<head>
<script type="text/javascript">/* Your script here */</script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
Above won't work for two reasons:
You run your script before you load the jQuery, so commands like $(".class") aren't understood.
You run your script before loading the content, so for example var $input_class = $('.addCheckbox'); will be empty, because the element with class addCheckbox doesn't exist yet. [for this one assume jQuery is included before the script, but the script is still inside the <head>].

Print a div content using Jquery

I want to print the content of a div using jQuery. This question is already asked in SO, but I can't find the correct (working) answer.
This is is my HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print'>
</div>
<p>Do not print.</p>
Here I want to print the content of the div printarea.
I tried this:
$("#btn").click(function () {
$("#printarea").print();
});
But it gives a console error when the button is clicked:
Uncaught TypeError: $(...).print is not a function
But when I am trying to print the entire page using
window.print();
it is working. But I only want to print the content of a particular div. I saw the answer $("#printarea").print(); in many places , but this is not working.
Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).
And it is working well...
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>
JavaScript
function printDiv()
{
var divToPrint=document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){newWin.close();},10);
}
https://github.com/jasonday/printThis
$("#myID").printThis();
Great jQuery plugin to do exactly what you're after
If you want to do this without an extra plugin (like printThis), I think this should work. The idea is to have a special div that will be printed, while everything else is hidden using CSS. This is easier to do if the div is a direct child of the body tag, so you will have to move whatever you want to print to a div like that. S So begin with creating a div with id print-me as a direct child to your body tag. Then use this code to print the div:
$("#btn").click(function () {
//Copy the element you want to print to the print-me div.
$("#printarea").clone().appendTo("#print-me");
//Apply some styles to hide everything else while printing.
$("body").addClass("printing");
//Print the window.
window.print();
//Restore the styles.
$("body").removeClass("printing");
//Clear up the div.
$("#print-me").empty();
});
The styles you need are these:
#media print {
/* Hide everything in the body when printing... */
body.printing * { display: none; }
/* ...except our special div. */
body.printing #print-me { display: block; }
}
#media screen {
/* Hide the special layer from the screen. */
#print-me { display: none; }
}
The reason why we should only apply the #print styles when the printing class is present is that the page should be printed as normally if the user prints the page by selecting File -> Print.
None of the solutions above work perfectly.They either loses CSS or have to include/edit external CSS file. I found a perfect solution that will not lose your CSS nor you have to edit/add external CSS.
HTML:
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p
Javascript:
function printFunc() {
var divToPrint = document.getElementById('printarea');
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}
Without using any plugin you can opt this logic.
$("#btn").click(function () {
//Hide all other elements other than printarea.
$("#printarea").show();
window.print();
});
Below code from codepen worked for me as I wanted,
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
$('button').on('click',function(){
printData();
})
Here is a link codepen
I update this function
now you can print any tag or any part of the page with its full style
must include jquery.js file
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printtag("DivIdToPrint");' >
JavaScript
function printtag(tagid) {
var hashid = "#"+ tagid;
var tagname = $(hashid).prop("tagName").toLowerCase() ;
var attributes = "";
var attrs = document.getElementById(tagid).attributes;
$.each(attrs,function(i,elem){
attributes += " "+ elem.name+" ='"+elem.value+"' " ;
})
var divToPrint= $(hashid).html() ;
var head = "<html><head>"+ $("head").html() + "</head>" ;
var allcontent = head + "<body onload='window.print()' >"+ "<" + tagname + attributes + ">" + divToPrint + "</" + tagname + ">" + "</body></html>" ;
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write(allcontent);
newWin.document.close();
// setTimeout(function(){newWin.close();},10);
}
First include the header
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script type="text/JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.6.0/jQuery.print.js"></script>
As you are using a print function with a selector which is a part of print.js so you need to call them before you use it...
Else
window.print()
will do it
$("#btn").click(function () {
$("#printarea").print();
});
or
$("#btn").on('click',function () {
$("#printarea").print();
});
use this library : Print.JS
with this library you can print both HTML and PDF.
<form method="post" action="#" id="printJS-form">
...
</form>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
</div>
<input type='button' id='btn' value='Print' onlick="printDiv()">
<p>Do not print.</p>
function printDiv(){
var printContents = document.getElementById("printarea").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
This Above function should be load on same page.
I tried all the non-plugin approaches here, but all caused blank pages to print after the content, or had other problems. Here's my solution:
Html:
<body>
<div id="page-content">
<div id="printme">Content To Print</div>
<div>Don't print this.</div>
</div>
<div id="hidden-print-div"></div>
</body>
Jquery:
$(document).ready(function () {
$("#hidden-print-div").html($("#printme").html());
});
Css:
#hidden-print-div {
display: none;
}
#media print {
#hidden-print-div {
display: block;
}
#page-content {
display: none;
}
}
Take a Look at this
Plugin
Makes your code as easy as -> $('SelectorToPrint').printElement();
Print only selected element on codepen
HTML:
<div class="print">
<p>Print 1</p>
Click Me To Print
</div>
<div class="print">
<p>Print 2</p>
Click Me To Print
</div>
JQuery:
$('.js-print-link').on('click', function() {
var printBlock = $(this).parents('.print').siblings('.print');
printBlock.hide();
window.print();
printBlock.show();
});
CSS CODE
<style type="text/css">
table {border-collapse: collapse; width: 100%; margin-bottom: 10px; width: 450px;}
table, th, td {border: 1px solid #000000;}
#media print {
.print-btn{
display: none;
}
}
</style>
HTML CODE
<table>
<tbody>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody>
</table>
<button class="print-btn" onclick="window.print()">Print me</button>
OUTPUT

<Div style=> not changing the font

I am loading external html files with the following script:
<script type="text/javascript">
$(document).ready(function(){
$("#page1").click(function(){
$('#result').load('140314F00604.htm');
//alert("Thanks for visiting!");
});
$("#page2").click(function(){
$('#result').load('140314F029.htm');
//alert("Thanks for visiting!");
});
$("#page3").click(function(){
$('#result').load('140221F193.htm');
//alert("Thanks for visiting!");
});
});
</script>
<table cellpadding="0" cellspacing="0" style="width: 100%; border-size: 1px">
<tr>
<td><a id="page1" href="#">About</a></td>
<td><a id="page2" href="#">Community</a></td>
<td><a id="page3" href="#">Sponsor</a></td>
</tr>
</table>
<div id="result" style="color:red; font-style:italic; font-family:Arial; font-size:12px;"></div>
It works perfectly. Load the html file, changes the font color, italic and size, but it does not seem to want to change the font itself to Arial.
The imported HTML looks like this:
The imported html is generated by software and it can not be edited in the program itself therefore I am trying to load it and change its formatting.
The script below worked perfectly. Unfortunatly the imported html uses spaces to aligh text. Obviously this can not be changed. The working script messes the spacing if you change the font from courier to anything else as can be seen on the images. Is it posible to fix this?
function applyPreFont(){
var oldHtml = $('#result pre').html();
$('#result pre').html('<div class="pre-div">' + oldHtml + '</div>');
}
function LoadExternalContent(pagename){
$('#result').load(pagename, function(data) {
applyPreFont();
// do other stuff
});
}
$(document).ready(function(){
$("#page1").click(function(){
LoadExternalContent('140314F00604.htm');
});
$("#page2").click(function(){
LoadExternalContent('140314F029.htm');
});
$("#page3").click(function(){
LoadExternalContent('140221F193.htm');
});
});
Original html file
The output from the script
pre does not accepted css font styling so well. The fonts properties will be bypassed, even inherited from parent elements. Even trying to applied it to parent element won't work.
UPDATE 1
Caution:
pre element uses a font of type monospace (All glyphs have the same fixed width), which makes easy for tabular data. Mostly of the fonts (as Arial, Helvetica, Verdana, Times New Roman..) are not monospace, so, each glyph has it own size according to its width.
In the end, the tabular data will not be so "tabular" anymore if you apply non-monospace font. More on MDN Docs.
You'll have to apply css to a descendant element in pre.
As you are using jQuery (and html is dynamic), you can wrap pre content into a new div with jQuery and apply CSS to its new element:
var oldHtml = $('#result pre').html();
$('#result pre').html('<div class="pre-div">' + oldHtml + '</div>');
resulting something like this:
<pre>
<div class="pre-div">
Boland Athletics ...
...
</div>
</pre>
I suggest you code like this:
function applyPreFont(){
var oldHtml = $('#result pre').html();
$('#result pre').html('<div class="pre-div">' + oldHtml + '</div>');
}
function LoadExternalContent(pagename){
$('#result').load(pagename, function(data) {
applyPreFont();
// do other stuff
});
}
$(document).ready(function(){
$("#page1").click(function(){
LoadExternalContent('140314F00604.htm');
});
$("#page2").click(function(){
LoadExternalContent('140314F029.htm');
});
$("#page3").click(function(){
LoadExternalContent('140221F193.htm');
});
});
CSS:
.pre-div {
font-family: arial;
font-weight: bold;
}
See an example in fiddle
** Tested only in Chrome.
The $.load method in jquery has another overload that passes in a callback function. In the documentation, "If a 'complete' callback is provided, it is executed after post-processing and HTML insertion has been performed.".
I believe you should change your load methods to look like:
$('#result').load('140221F193.htm', function(){
//alert("Thanks for visiting!");
//set css here
});
UPDATE:
If you would like everything to align (since PRE uses a Mono Space font) try downloading the Monospace version of Arial (Download Here make sure to click the actual download to the right of the font)
the way you would implement it based on your accepted answer and not the removal of the pre tag is through css is:
#font-face
{
font-family: arialMono;
src: url(/directory/locationOfFontFile.ttf);
}
.pre-div{
font-family: arialMono;
}
Through your Jquery function (after the font is added to a stylesheet) it would be implemented like so:
function applyPreFont(){
var oldHtml = $('#result pre').html();
$('#result pre').html("")
$("<div />",{
"class": "pre-div",
html: oldHtml,
css: {
"font-family": "arialMono"
}
}).appendTo($('#result pre'));
$('#result pre').html('<div class="pre-div">' + oldHtml + '</div>');
}
The problem is with the <pre> tags (Preformatted Text). Styling that is going to be buggy because of the nature of the tags. Your best bet is to remove the Pre tags via jquery:
$('#result').load('140221F193.htm', function(){
$("#result pre").contents().unwrap()
});
That should remove the PRE tags and render the html successfully :)
JSFidde Here

How to remove Options from multiselect dropdown in Jquery

I have some table column with some preselected values and now i want to remove those selected values from dropdown(ddlMultiselect) .. Both table column and dropdown option values are same and what i want that those values should be hide/remove from dropdown as per if condition.
$('#sometabletr:gt(0)').each(function () {
var row = $('td:eq(0) > span', this).text();
$('#ddlMultiselect :selected').each(function () {
var col = $(this).val();
if (row == col) {
$(this).remove();
}
});
});
This is the way is do it, fast and easy way
$('#listname option:selected').each(function (index, option) {
$(option).remove();
});
There is another way to approach this issue.. but setting up classes on the table rows, all you have to do is change the class of the table element itself to hide/show vast amounts of things while only doing a single repaint, which GREATLY improves performance.
In this example, I have the adding of a class hard-coded, but you could use jQuery's addClass and removeClass or look up the best alternatives available.
<doctype html>
<html>
<header>
<title>Demo HIde</title>
<style>
#mytable.even tr.odd {
display:none;
}
</style>
</header>
<body>
<table id="mytable">
<tr class="odd"><td>1</td></tr>
<tr class="even"><td>2</td></tr>
<tr class="odd"><td>3</td></tr>
<tr class="even"><td>4</td></tr>
<tr class="odd"><td>5</td></tr>
<tr class="even"><td>6</td></tr>
</table>
<script>
// Show the even values only
document.getElementById("mytable").className += " even";
</script>
</body>
</html>

In my case, How to highlight table row when mouseover?

In my index.html page, I have an empty table defined as following:
<body>
...
<table width="500" border="0" cellpadding="1" cellspacing="0" class="mytable">
<tr></tr>
</table>
<script src="my.js"></script>
</body>
As you saw above, there is an JavaScript file my.js is included.
my.js(which is used to update the table row):
var items = ARRAY_OF_OBJECTS_FROM_SERVER; //e.g. items=[{'John', '023567'},{'Bill', '055534'},...];
//Each object element in the "items" array contain "name" and "phone" attribute.
var mytable = $('.mytable tr:first');
for(var i=0; i<items.length; i++){
var obj = items[i];
mytable.after("<tr>");
mytable.after("<td> </td>");
mytable.after(" <td>"+obj.name+"</td>");
mytable.after("<td>"+obj.phone+"</td>");
mytable.after("</tr>");
}
I successfully get the dynamical table working, but when I try to add mouse hover effect on each row, I just failed. What I tried is by using CSS:
.mytable tr:hover
{
background-color: #632a2a;
color: #fff;
}
I would like the mouse hover with color highlight effect to be working on IE 7+, firefox and chrome, what is the correct way to implement the table row mouse hover effect in my case??
----EDIT----
Here is my index.html page:
index.html
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>my test</title>
<link href="mystyle.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<table width="500" border="0" cellpadding="1" cellspacing="0" class="mytable">
<tr>
</tr>
</table>
<script src="my.js"></script>
</body>
</html>
--SOLUTION----
#manji 's solution solved my problem. That's change in JavaScript to use append instead of after inside for loop. Then, the CSS way of highlighting row is working.
You are writing the <td> outside of <tr> with this:
mytable.after("<tr>");
mytable.after("<td> </td>");
mytable.after(" <td>"+obj.name+"</td>");
mytable.after("<td>"+obj.phone+"</td>");
mytable.after("</tr>");
For example, first one will add a <tr> and close it, then 3 closed <td>s before the <tr> and the last one is incorrect and will have no effect.
Try it this way and it will work:
mytable.after("<tr>"
+"<td> </td>"
+"<td>"+obj.name+"</td>"
+"<td>"+obj.phone+"</td>"
+"</tr>");
and it's better to use .append() (it will add the objects in their list order):
var mytable = $('.mytable'); // mytable selector is changed to select the table
// you can remove the empty <tr>
for(var i=0; i<items.length; i++){
var obj = items[i];
mytable.append("<tr>"
+"<td> </td>"
+"<td>"+obj.name+"</td>"
+"<td>"+obj.phone+"</td>"
+"</tr>");
Try the following:
.mytable tr:hover td
{
background-color: #632a2a;
color: #fff;
}
Given your list of browser support, CSS is the proper solution. It's important to note that the cells (<td>) cover the row (<tr>). So it's their background that you want to modify.
You're best bet is to use jquery's hover: Click Here
IE 7 did not have hover support on elements other than anchor tags. (or maybe that was just 6) either way, since you are using jquery already you can get your hover effect done easily.
$("tr").hover(
function () {
$(this).addClass('hover_class');
},
function () {
$(this).removeClass('hover_class');
}
);
Note: IE 7 will only allow :hover if you are running in HTML 4.01 STRICT for your doctype. Otherwise you need to use javascript to accomplish what you are looking to do.
If you cannot get the css solution to work use a delegate function to handle the dynamic rows.
$("table.mytable").delegate("tr", "hover", function(){
$(this).toggleClass("hover");
});
jQuery:
$('.mytable tr').hover(function() {
$(this).addClass('active');
}, function() {
$(this).removeClass('active');
});
CSS:
.mytable tr.active td
{
background-color: #632a2a;
color: #fff;
}
Check out the working example: http://jsfiddle.net/JpJFC/
Use jquery delegate method which is the best way to do it from performance point of view.
$(".mytable").delegate("tr", "mouseover", function(e) {
$(this).addClass('mouseoverClass');
});
$(".mytable").delegate("tr", "mouseout", function(e) {
$(this).removeClass('mouseoverClass');
});

Categories