Reputation: 82
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.
Upvotes: 0
Views: 76
Reputation: 10665
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);
}
Upvotes: 0
Reputation: 82241
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);
});
Upvotes: 3