Search code examples
jqueryslidetogglenextuntil

jQuery Next until current state hidden / show of child TR's


Hi all I have a slideToggle() function on a table which uses nextUntil to hide all child elements of a tr with a class of header, this works great.

But I need to get the current state of all the child tr's in order to find out if its children are hidden or visible the slideToggle / nextUntil function sets a style of display none for all child tr's up to the next tr with a class of header (tr.header) but leaves the td elements alone.

so I thought if I loop over the child elements and check the prop('nodeName') I could determine the current state i.e hidden or show - but I cannot seem to get it work.

There is probably an easier way to determine on click if you are showing or hiding something using slideToggle? The plan is to set local storage with a state value so when a user returns to the page the elements they have previously closed or opened maintain state.

$('.header').click(function(){

            $(this).nextUntil('tr.header').slideToggle(300);

            var count = 0;
            $.each($(this).nextUntil('tr.header'),function(){
                
                if($(this).prop('nodeName')  == 'TR' && $(this).is(':visible')){
                     count++;  
                }
                
            })

            console.log(count);

            if (count>0){
                alert('its been opened');
            
            }
            else{

                alert('its been closed');
                
            }

        });

Solution

  • How about this

    let headerAnimationProcessing, headerState = false;
    $('#header').click(function(){
        if( headerAnimationProcessing )
            return;
    
        headerAnimationProcessing = true;
        const $targets = $(this).nextUntil('tr.header');
        $targets[headerState ? 'slideUp' : 'slideDown' ](400, () => { headerAnimationProcessing = false; });
        headerState = !headerState;
    });