Issue
I'm trying to figure out how I can do this -- I need to keep one container open through a click of a sibling list item, but then close it on the second click. The issue is going back to another link and having a handler left on it.
The concept would be to have:
<ul id="nav">
<li><a href="#">Nav Item Two</a></li>
<li><a href="#">Nav Item Three</a></li>
<li><a href="#">Nav Item Four</a></li>
</ul>
<div id="nav-content">
<!-- Content changed with Ajax -->
</div>
Using this, I'm interchanging the content with ajax, so a click returns it into my "nav-content" div. When I click on one item, I want the content div to open, and then remain open when the next nav item link is clicked, but closed when it's clicked a second time.
Tried using unbind but I don't think that's appropriate, and it didn't work. Any ideas?
Solution
You can do this by:
- giving the
lia class when you click it - removing that class from all other
lis - then checking for that class before you hide or show your div
Essentially using a class to keep up with which li was clicked last
$('#nav li').click(function(){
// remove the `active` cass form all `li`s in `#nav`
// except the one that was clicked
$('#nav li').not(this).each(function(){
$(this).removeClass('active');
});
// check if clicked element has `active` class
// if so it was just clicked for second time, close the div
if( $(this).hasClass('active') ){
$(this).removeClass('active');
$('#nav-content').hide();
}
else{
// if not it was clicked for the first time
// show the div and make the clicked element `active`
$(this).addClass('active');
$('#nav-content').show();
}
});
#nav-content{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="nav">
<li><a href="#">Nav Item Two</a></li>
<li><a href="#">Nav Item Three</a></li>
<li><a href="#">Nav Item Four</a></li>
</ul>
<div id="nav-content">
<!-- Content changed with Ajax -->
Here is some content
</div>
Answered By - Wesley Smith
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.