0

I have an anchor text that when click adds an active class to another class. I want to remove it when it has an active class or if I click the anchor text again. How can I do that?

HTML:

<a id="menu1" href="#menu">BUTTON</a>
<a class="mm-title">TITLE</a>

JAVASCRIPT:

 $(function(){
  $("#menu1").click(function(){
      $(this).addClass("active");
      $("a.mm-title").addClass("remove");
  });
 });

CSS:

.remove { display: none; }

Tried using this one but seems to have a problem with toggling back to inactive state. the 2nd click doesnt do anything but by the third time goes back to normal

JAVASCRIPT:

$(function(){
  $("#menu1").click(function(){
      $(this).toggleClass("active");
      $("a.mm-title").toggleClass("remove");
  });
 });

2 Answers 2

2

Try this

$(function(){
  $("#menu1").click(function(){
      $(this).toggleClass("active");
      $("a.mm-title").toggleClass("remove");
  });
 });

Let me know if it is helpful

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

3 Comments

toggleclass use for on off function? thanks works on my fiddle.
if it works, then please give a upvote and make this answer as a correct answer. So that, it may helpful someone else.. :)
Explain me what is the css property you want to assign for the active and inactive state to the anchor text, I'll tell you how to achieve that also
1

try this example

    <style type="text/css">
        .sector-active
        {
            color: green;
        }
    </style>
    <div class="container">
       <div class="main-sectors">
           <a href="#" class="sector-active">Name1</a>
           <a href="#" class="p-l-35">Name2</a>
           <a href="#" class="p-l-35">Name3</a>
           <a href="#" class="p-l-35">Name4</a>
           <a href="#" class="p-l-35">Name5</a>
       </div>
    </div>
   <script type="text/javascript" src="../library/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function()
        {
            $('a').click(function()
            {
                $(this).removeClass('p-1-35');
                $('a').removeClass('sector-active');
                $(this).addClass('sector-active');
            });
        });

    </script>

this code will be add sector-active class to clicked a tag and remove sector-active class from another a tag

if you can add sector-active class to all clicked a tag then comment to following line

// $('a').removeClass('sector-active');

this will help you

Comments

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.