jquery: don't run script, if it contains .active
I have a script that animates a menu. I don't want it to if the menu contains an object with an active class (.active). I can't figure it out. I have tried several things, but I guess I'm thinking all wrong. Can you help me?
This is the script:
$('#navigation .toplevel, #navigation > ul > li').each(function(idx) {
$(this).delay( idx * 600 ).fadeIn( 600 );
});
This is the markup:
<div id="navigation">
<a href="#" class="toplevel">Menu</a>
<ul class="undermenu">
<li><a href="#">1.0 Menuitem</a>
<ul>
<li><a href="#" class="active">1.1 Menuitem</a></li>
<li><a href="#">1.2 Menuitem</a></li>
</ul>
</li>
<li><a href="#">2.0 Menuitem</a>开发者_StackOverflow中文版;
<ul>
<li><a href="#">2.1 Menuitem</a></li>
<li><a href="#">2.2 Menuitem</a></li>
</ul> </li>
</ul>
</div>
If an UL does contain an active-class, I want it to be shown per default and the LI (the parent) to get an .active-class.
Does it make any sense?
*EDIT:*
The script shall not run if the main UL contains a child (or a childs child) with .active-class. I guess it's a IF/THEN matter? But I don't know how to write it.
And... If "UL LI UL LI A" is active the "UL LI" (parents, parents, parent :D) should be given .active class. How do I do this? Thank you in advance... :)First, to assign the .active
class to parent UL elements. You can simply change the selector below to iterate over your UL elements and add the .active
class to their parent LI elements:
$('#navigation > ul > li .active').each(function(){
$(this).parent().addClass('active');
});
This will ensure that none of your .active
tags are animated:
$('#navigation .toplevel, #navigation > ul > li').not('.active').each(function(idx) {
$(this).delay( idx * 600 ).fadeIn( 600 );
});
Add :not(.active)
to your selector.
You can try it with the :not() selector of jQuery.
http://api.jquery.com/not-selector/
e.g. selecting li's not containing class active: $('#navigation ul li:not(.active)').each...
Edit:
- you can add an if clause like this:
if($('#navigation ul .active').size() != 0)
{
$('#navigation .toplevel, #navigation > ul > li').each(function(idx)
{
$(this).delay( idx * 600 ).fadeIn( 600 );
});
}
2.
$('ul li').has('ul li a.active').addClass('active');
something like this should work.
check out: http://api.jquery.com/size/, http://api.jquery.com/addClass/, http://api.jquery.com/has/
I believe this is what you want.
$('#navigation .toplevel, #navigation > ul > li').each(function(idx) {
$this = $(this);
if( $this.find('li.active').length === 0 ) {
$this.delay( idx * 600 ).fadeIn( 600 );
}
});
精彩评论