I'm coding a calendar based system. It is displayed as a table. One event can occupy several different table cells, and I want to make all cells of a single event highlight on hover. I have done this several times before, but I am facing a new problem.
This time the calendar table, and it's contents, is dynamically generated, because it is a preview of potential conflicting events, when the user tries to save a new event.
I am using a data-value based on existing event-ids, as identifyers, when linking hover styles on elements. I trigger a mouseover and mouseout event, which toggles a "hovered" class on the elements that has the same data-value as the hovered element.
However, when I add the data-value to a table cell dynamically, it doesn't show up in the HTML of the relevant elements, in my chrome inspector. I can still select a relevant element, and check if it has the data-value through a console command line, and it does in fact have the data-value. But the hover styles, and the HTML displayed in the inspector, does not reflect that.
I've made a simplifyed fiddle, where I only have a simple button, adding '1' as a data-value to four of six table cells. Below the dynamic table, is a static table which already has the data-values. Note that the hover style links are not initiated before clicking the button. After clicking the button, the static table has working hover-linking, while the dynamically updated table does not. Well, it works in one way. Hovering elements from the dynamic table, will ssuccessfully link to, and only to the static table. This leads me to believe that it is the CSS-selection of dynamically updated elements with data-value that fails.
Note that the single element with an id, from the dynamic table, reports that the data-value is in fact set on it.
How can I make my dynamic table work, so that hover linking is visible?
HTML:
<button onclick="add_data()">
Add Data (and hover links)
</button>
<table>
<tr>
<td class="taken"></td>
<td class="taken" id="random-td"></td>
<td class="taken"></td>
</tr>
<tr>
<td></td>
<td></td>
<td class="taken"></td>
</tr>
</table>
<br/>
<table>
<tr>
<td class="taken" data-value="1"></td>
<td class="taken" data-value="1"></td>
<td class="taken" data-value="1"></td>
</tr>
<tr>
<td></td>
<td></td>
<td class="taken" data-value="1"></td>
</tr>
</table>
Javascript:
window.add_data = function(){
console.log($('#random-td').data('value')); //undefined
$('.taken').data("value", 1);
$("td.taken").mouseover(function(){
var value = $(this).data("value");
$("td.taken[data-value='1']").toggleClass("hovered");
});
$("td.taken").mouseout(function(){
var value = $(this).data("value");
$("td.taken[data-value='1']").toggleClass("hovered");
});
console.log($('#random-td').data('value')); // 1
}
CSS:
td{
width: 50px;
height: 20px;
}
td.taken{
background-color: #19b4e0;
}
td.taken.hovered,
td.taken:hover{
background-color: #75D2EC;
}