0

I'm using following JavaScript code to slideUp and slideDown different divs based on theirs link options:

Javascript / jQuery:

function toggleDiv(option) {
    $('.content-box').slideUp();
    $('#' + option).slideDown(300);
}

HTML:

<li><a class="active" href="javascript:toggleDiv('toggle1')">Toggle 1</a></li>
<li><a href="javascript:toggleDiv('toggle2')">Toggle 2</a></li>

The whole code works perfectly, however what I would like to do is that the class="active" switches to the actual link that user has pressed. I heard about some attribute method or something similiar bur have no ideea how to proceed. So I would appriciate any help from you.

By the way, why is the code working smoothly in Firefox/Chrome but is laggy in Safari?

Check the JSFiddle here: https://jsfiddle.net/3vfwdL34/ For some reason it won't work in JSFiddle but the same code works fine in a normal .html file.

2 Answers 2

3

You need to define the function before using them in inline event. wrap the code in head section and everything should work fine for you. and for adding the class active, pass current clicked object to method and add class to it.

<head>
  <script>
    function toggleDiv(option,that) {
       $('.active').removeClass('active');
       $(that).addClass('active');
       $('.content-box').slideUp();
       $('#' + option).slideDown(300);
    }
  </script>
</head>

However you can use jquery to simplfy the task:

$('li a').click(function(){
   $('.active').not(this).removeClass('active');
   $(this).addClass('active');
   $('.content-box').slideUp();
   $('#toggle'+($(this).parent().index()+1)).slideDown(300);
});

Demo

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

1 Comment

I think the OP had formatting issues when posting this question. I don't think this is the issue as the javascript/jQuery wouldn't work at all and the OP has clearly pointing out "The whole code works perfectly".
0

Try like this:

function toggleDiv(option) {
    //move the class 'active' to the pressed li
    ("a").removeClass("active")
    $('#' + option).addClass("active")

    $('.content-box').slideUp();
    $('#' + option).slideDown(300);
}

1 Comment

Your code works but not entirely, I changed li to a and it removed the class, but it did not add a new class to the new link

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.