0

Basically I have some links which include some other links, I'm trying to show the parent links only and when one clicks on the parent link the child links should appear and when one clicks on the parent link again the child link should disappear,

the code works for the first click and it opens the relevant child links but how do I make them disappear when I click on the parent link again,

thanks for the help.

jQuery.noConflict();

jQuery(document).ready(function(e) {

jQuery('.nav-container ul.level0 li.level1 a').click(function(e) {

    e.preventDefault();
    jQuery(this).css({'background':'#000000','color':'#ffffff'});
    jQuery('.nav-container ul.level0 li.level2 a').css('display','block');

});

});

2 Answers 2

1

Use jquery toggle function.

Sign up to request clarification or add additional context in comments.

Comments

0

A simple way to do this would be creating an attribute to be read on the item you have clicked.

jQuery.noConflict();

jQuery(document).ready(function(e) {

    jQuery('.nav-container ul.level0 li.level1 a').click(function(e) {
        if(jQuery(this).attr('sel') != 'true')
        {
            e.preventDefault();
            jQuery(this).attr('sel','true');
            jQuery(this).css({'background':'#000000','color':'#ffffff'});
            jQuery('.nav-container ul.level0 li.level2 a').css('display','block');
        } else {
            jQuery(this).attr('sel','');
            // do close code
        }
    });

});

Where the attribute 'sel' could be something else like 'pushed', or 'dropped'... just might want to watch from using things like 'selected', 'click', or others that could confuse HTML. Also I would not use 'class' since you could have multiple classes on an object and it would return this.

<div class="selected item"></div>
jQuery(this).attr('class') = 'selected item';

2 Comments

A performance comment. It's much faster to alias jQuery(this) or $(this) in a variable. So do a var $el = $(this) at the top of your click function and then refer to this variable.
@Keltex - Thank you for this comment, but it is actually the OP's code that I rewrote with my additions to it. I didn't change the original code as to not confuse the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.