Difficulty changing dynamically generated table cell background onclick - javascript

I'm working on making a pixel art painter, and this is beyond puzzling.
As of right now, I have a table that is being dynamically generated based on user specified amounts for "Rows" and "Columns" This works perfectly fine (Although it doesn't seem to work in JSFiddle, but I can assure you that it does indeed work on a webpage as you can see here on my test site ).
What I'm trying to accomplish now can be seen in this fiddle
Pretty straight forward, trying to change "TD" tag's css onclick.
I can't seem to get that functionality working with a dynamically generated table.
Here is what I am currently trying (JSFiddle)
HTML:
Row Count:<input type="text" id="rowcount" />
Column Count:<input type="text" id="columncount" />
<input type="button" onclick="createTable();" value="Create Table" />
<div id="box"></div>
CSS:
table{
width:500px;
height:500px;
}
td{
padding:10px;
margin:10px;
border:1px solid #ccc;
}
.active {
background-color:#aaa;
}
JS/jQuery:
function createTable() {
mytable = $('<table></table>').attr({
id: "basicTable"
});
var rows = new Number($("#rowcount").val());
var cols = new Number($("#columncount").val());
var tr = [];
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').attr({
class: ["class1", "class2", "class3"].join(' ')
}).appendTo(mytable);
for (var j = 0; j < cols; j++) {
$('<td></td>').text("text1").appendTo(row);
}
}
console.log("TTTTT:" + mytable.html());
mytable.appendTo("#box");
}
$(function () {
$('td').click(function () {
$(this).toggleClass('active');
});
});
Any help or suggestions are greatly appreciated.

Yes it won't work. Since the entire table are created dynamically they are not getting attached to the document (ie., The problem with dynamically created elements, is that they aren't born with the same event handlers as the existing elements. ).
So you have to go for event delegation attached to document.
$(function () {
$(document).on('click', 'td', function () {
$(this).toggleClass('active');
});
});
JSFiddle
Hope you understood.

You are binding click on 'td' before 'td' is created. Bind click inside createTable() method after 'td's have been added to the DOM.
function createTable()
{
// your code
$('td').click(function ()
{
$(this).toggleClass('active');
});
}
Adding jsfiddle link.
http://jsfiddle.net/y94K8/4/

Related

Remove class before clicking on another table row HTML CSS JAVASCRIPT

The below code retrieves the table html element and contains an onclick function. On this it calls a bunch of functions which works completely fine. The last part of the function is to highlight the table row using the class .primary. There should only ever be one row highlighted with this class. How do I change the function so that it removes the class before you click on another row. At the moment if you click on a row it highlights the entire row yellow. But when you click on another row it also highlights thats one yellow. I just want one row to be highlighted each time:
var table = document.getElementById("tabledt");
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
if (this.classList.contains('selected')) {
highlightMarker(prevHighlightMarker, false);
tableText(this);
highlightMarker(cMarkers[$(this).data('id')], true);
this.classList.add("primary");
}
};
}
}
.primary {
background-color: yellow !important;
}
I think you are using jquery. There is a function in jquery that is useful in this cases.
siblings()
siblings selects all the all the elements with same parent. and you can filter it as you wish. https://api.jquery.com/siblings/
In this case you can do this way:
$("#tabledt tr").click(function(){
$(this).siblings('tr').removeClass('primary');
}

JS changes width of tbody?

I have an table in my HTMl view (php mvc).
The table displays some basic information in a row.
By clicking the 'More' botton (+) you can see other information belonging to this user.
But somehow activating the JS chances the width of the affected row and the rows below, and slightly the first row.
How is this possible? And how can I prevent this?
Any help is welcome.
The code is in a fiddle here https://jsfiddle.net/jdkosnl/e71ms5ar/41/
$(document).ready(function () {
$('.show-more-button').click(function () {
var $this = $(this);
var forId = $(this).data('more-for');
var $showMoreElement = $(this).closest('table').children('.show-more[data-more-id="' + forId + '"]');
if ($this.hasClass('fa-plus-square')) {
$this.removeClass('fa-plus-square').addClass('fa-minus-square');
$showMoreElement.css('display', 'block');
} else if ($this.hasClass('fa-minus-square')) {
$this.removeClass('fa-minus-square').addClass('fa-plus-square');
$showMoreElement.css('display', 'none');
}
});
});
Try to avoid using display: block when working with tables and their elements. The suitable value for tbody is 'table-row-group' (instead of 'block'). Like this:
if ($this.hasClass('fa-plus-square')) {
$this.removeClass('fa-plus-square').addClass('fa-minus-square');
$showMoreElement.css('display', 'table-row-group');
}
JSFiddle.

Changing table cell colors in Javascript without the use of id's

I'm working on a small project where I'd like to change the background color of a table's cells while the mouse hovers over each cell. I'm able to do it with an individual cell with document.getElementById("cell1"); etc. but haven't found a way to make life easier by selecting all of the td tags and avoiding giving each cell its own id. I've tried document.getElementsByTagName but the console returns that cell.addEventListener is not a function. I must be using the selectors wrong or am not understanding the correct usage of event handling. I've found a similar question on here but it doesn't address using solely javascript which i'd like to do.
var cell = document.getElementsByTagName("td");
cell.addEventListener("mouseover", function() {
this.style.backgroundColor="red";
cell.addEventListener("mouseout", function() {
this.style.backgroundColor="";
})
});
Why not CSS? The :hover pseudo class is much easier and conserves code length and complexity, and is ultimately faster.
td:hover{ /* insert proper selector here */
background-color:red;
}
You should be iterating the set. "The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name." - https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
for(var i = 0; i < cell.length; i++){
cell[i].addEventListener("mouseover", function() {
this.style.backgroundColor="red";
};
cell[i].addEventListener("mouseout", function() {
this.style.backgroundColor="";
});
}
However, a better way to do this would be a simple hover rule in css
td:hover{
background-color: red;
}
Here is a jQuery solution
$(document).ready(function() {
$("td").on("mouseover mouseout", function() {
$(this).toggleClass("red");
});
});
http://jsfiddle.net/kwagtd0d/1
You can add and remove classes with jQuery by listening for events, but it's easiest to do this with css.
td:hover
JavaScript solution
var cells = document.getElementsByTagName("td");
This returns a collection of td elements. We can now iterate through this selection.
for(var i = 0; i < cells.length; i++){
cells[i].addEventListener("mouseover", function() {
this.classList.add("red");
};
cells[i].addEventListener("mouseout", function() {
this.classList.remove("red");
});
}
http://jsfiddle.net/qknjyaaw/

Hide a table row with filtering jquery

I have the following example http://jsfiddle.net/zidski/MxqRu/1/
When you click on 2010 I need valuation to disappear with the list items.
Here is the code which I am using to do this:
$("#yearfilter a").live("click", function(e) {
e.preventDefault();
//var v = $(this).val();
var v = $(this).attr("data-value");
if(v.length > 0) {
$('tr.reports').show();
$('tr.reports ul').hide();
$('tr.reports ul.year-'+v).show();
$('tr.reports').each(function() {
if($('ul:visible', this).size() == 0) {
$(this).hide();
}
});
} else {
$('tr.reports').show();
$('tr.reports ul').show();
}
});
I have done it in my project something like this:
function toggleRow(row_id) {
row_selector = "#row_" + row_id;
$(row_selector).toggleClass("shown hidden")
}
Then in the CSS:
.hidden {display:none;}
.shown {}
Then in the HTML I have alternating table rows, where the odd rows act as headings for the content in the even rows. Clicking an odd row toggles the visibility of the corresponding even row.
...
<tr onclick="toggleRow(17)">...</tr>
<tr class="hidden" id="row_17">...</tr>
...
Give each tr an ID something like id="row_2010" then look for that and hide the whole entire row at once.
UPDATE
I would strongly suggest not using so many tables and use more classes to classify your data structure. It would help your javascript be much more clean, concise and function easier.
UPDATE
I adjusted all your javacsript and some of your html. Here is a fully working example jsFiddle Demo

How can I highlight a table row using Prototype?

How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag?
An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful.
<table id="mytable">
<tbody>
<tr><td>Foo</td><td>Bar</td></tr>
<tr><td>Bork</td><td>Bork</td></tr>
</tbody>
</table>
<script type="text/javascript">
$$('#mytable tr').each(function(item) {
item.observe('mouseover', function() {
item.setStyle({ backgroundColor: '#ddd' });
});
item.observe('mouseout', function() {
item.setStyle({backgroundColor: '#fff' });
});
});
</script>
You can use Prototype's addClassName and removeClassName methods.
Create a CSS class "hilight" that you'll apply to the hilighted <tr>'s. Then run this code on page load:
var rows = $$('tbody tr');
for (var i = 0; i < rows.length; i++) {
rows[i].onmouseover = function() { $(this).addClassName('hilight'); }
rows[i].onmouseout = function() { $(this).removeClassName('hilight'); }
}
A little bit generic solution:
Let's say I want to have a simple way to make tables with rows that will highlight when I put mouse pointer over them. In ideal world this would be very easy, with just one simple CSS rule:
tr:hover { background: red; }
Unfortunately, older versions of IE don't support :hover selector on elements other than A. So we have to use JavaScript.
In that case, I will define a table class "highlightable" to mark tables that should have hoverable rows. I will make the background switching by adding and removing the class "highlight" on the table row.
CSS
table.highlightable tr.highlight { background: red; }
JavaScript (using Prototype)
// when document loads
document.observe( 'dom:loaded', function() {
// find all rows in highlightable table
$$( 'table.highlightable tr' ).each( function( row ) {
// add/remove class "highlight" when mouse enters/leaves
row.observe( 'mouseover', function( evt ) { evt.element().addClassName( 'highlight' ) } );
row.observe( 'mouseout', function( evt ) { evt.element().removeClassName( 'highlight' ) } );
} );
} )
HTML
All you have to do now is to add class "highlightable" to any table you want:
<table class="highlightable">
...
</table>
I made a slight change to #swilliams code.
$$('#thetable tr:not(#headRow)').each(
This lets me have a table with a header row that doesn't get highlighted.
<tr id="headRow">
<th>Header 1</th>
</tr>
You can do something to each row, like so:
$('tableId').getElementsBySelector('tr').each(function (row) {
...
});
So, in the body of that function, you have access to each row, one at a time, in the 'row' variable. You can then call Event.observe(row, ...)
So, something like this might work:
$('tableId').getElementsBySelector('tr').each(function (row) {
Event.observe(row, 'mouseover', function () {...do hightlight code...});
});
I found ab interesting solution for Rows background, the rows highlighting on mouse over, without JS. Here is link
Works in all browsers. For IE6/7/8 ...
tr{ position: relative; }
td{ background-image: none }
And for Safari I use negative background position for each TD.

Categories