Bind events to display:none; elements

on page load are jQuery events bound to elements that are set to display:none;?

if not…

I am toggling a class to apply display:block;. Would it be safe to bind the event right after the class is applied?

thanks in advance.

Events should not care if the element is hidden or not, you should always bind events without the knowledge of what the element state is as that ensures it will always fire as expected. However in saying that jQuery has event delegation which allows for real time element event binding but its not designed to detect style changes on elements, instead you should delegate an event to watch for the given class name which eliminates the risk of multiple events been bound to the same element more than once.

I don’t fully understand your answer so here is some more code to explain.

I’m dealing with nested site navigation on an iphone. Here’s a snippet:


<nav>
                <ul>
                    <li><a href="#" class="sub">Level 1</a>
                        <ul>
                            <li><a href="#">Level 2</a>
                                <ul>
                                    <li><a href="#">Level 3</a></li>
                                    <li><a href="#">Level 3</a></li>
                                </ul>
                            </li>
                        </ul>
                    </li>
                    <li><a href="#">Level 1</a></li>
                    <li><a href="#">Level 1</a></li>
                </ul>
            </nav>

by default Level 2 and Level 3 navigation are display:none;

when you click a Level 1 anchor, that will also have class=“sub”, I was running this code:


$('a.sub').click(function(e){
        e.preventDefault();
        $(this).parent().toggleClass('showSub');
 })

to add the class “showSub”, and CSS would then reveal the Level 2 navigation.

and that worked fine.

what didn’t work was revealing the level 3 navigation at first.

orignially I used the same technique above to show level 3 navigation after clicking a Level 2 link. The problem was this js ran when the page loaded, but when it ran the elements it was bound to were display:none; so the event was not attached for me:


$('level 2 selector here').click(function(e){
            e.preventDefault();
            $(this).parent().addClass('showSubSub');
            
})

i was only able to get it to work after I nested these functions as to attached a click event to level 2 anchors after the display was no longer block:


$('a.sub').click(function(e){
        e.preventDefault();
        $(this).parent().toggleClass('showSub');
        
        
        $('level 2 selector here').click(function(e){
            e.preventDefault();
            $(this).parent().addClass('showSubSub');
        })
        
        
    })

I’m not sure if this follows what you explained above. But if there is a better way to do this please let me know!

Thanks