Search code examples
jqueryhtml-tablecalendarjquery-selectorstablerow

jQuery next() td across table rows


I have designed a custom calendar using html and jQuery. I want to highlight a range of k days (say 2 days) onhover on the start date. Available dates in my calendar are td of class 'available'. This is the code snippet i am using:

$(".monthly-calendar .available").hover(function() {
    $(this).toggleClass("selected");
    $(this).next(".available").toggleClass("selected");
}

Unfortunately next() only works for the parent row. This creates a problem when i hover on the last column in a row, in which case i see only 1 column highlighted. How do I overload next() to select available TDs across subsequent rows ?

The fiddle is available on http://jsfiddle.net/yL573/1/ Try hovering on 26th to see the problem. Hovering on 26 should also highlight 27 or the next 'available' td. I want to generalize this for selection of k days (k>1, in this case k=2)


Solution

  • could it be something like this? i made a quick jsfiddle for your concept

    it works even over different rows, and even if some days in the middle are already unavailable (not have the class available)

    http://jsfiddle.net/dP3Bk/1/

    let me know if this is what you expect it to do

    it comes down to not taking .next() but using the index of the element in the array of all <td> elements.

    javascript:

    $('#tableid td.available').hover(function(){
        // mouse in
        var available = $('#tableid td.available');
        var i = available.index($(this));
        $(available[i]).add($(available[i+1])).addClass('current');
    }, function(){
        // mouse out
        $('td.current').removeClass('current');
    });
    

    remark if you have a lot of elements this can be a performance hit. in any case, i'd add the id of the table in front of your selectors, not to work with all td.available elements.