Edoras Edoras - 26 days ago 10
Javascript Question

AddClass "active" where Class is same as href, otherwise remove "active"

I'm doing probably something wrong, if I will click on

<a>
tag with class "sw" and
href="#m1"
, I need remove class "active" from all
<a>
and
<div>
tags with class "sw", but also I need add "active" to all rest
<a>
and
<div>
tags with class which is same as href in
<a>
link, where I am clicking.

Thats mean, I need remove hash from href, because I am looking for that class not ID.

for example:

<a href="#m1" class="sw">CL1<a/>
<a href="#m2" class="sw active">CL2<a/>
<div class="sw m1>HELLO1</div>
<div class="sw m2 active>HELLO2</div>


if I will click on CL1, then I need remove all active from all sw divs and a, but also I need addclass "active" to all divs and a where is #m1 as class.

I hope u will underestand me :(

Here is my 2 testing codes ...

$('a.sw').on('click', function() {
var nohash = $(this).attr('href').replace('#', '');
if ( !$( this ).hasClass( "active" ) ) {
$('.sw').each(function() {
if($(this).hasClass('active')) {
$(this).removeClass('active');
} else {
nohash.addClass('active');
}
});
}
});

$( 'a.sw' ).on( 'click', function() {
$('div.sw').removeClass( 'active' );
$(this).href().replace('#', '').addClass( 'active' )
});

Answer

Take moment and read Decoupling Your HTML, CSS, and JavaScript - Philip Walton @ Google

Based on your current code, you have a very high degree of coupling and virtually no reuse of your code. Here is how I would refactor it:

html:

<a href="#m1" class="js-sw active" data-sw-target=".sw-target-m1">CL1</a>
<a href="#m2" class="js-sw" data-sw-target=".sw-target-m2">CL2</a>
<div class="sw-target sw-target-m1 active">HELLO1</div>
<div class="sw-target sw-target-m2">HELLO2</div>

Javascript:

$(document).ready(function() {
  $('.js-sw').on('click', function() {
    $('.sw-target, .js-sw').removeClass('active');

    $(this).addClass('active');
    var selector = $(this).data('sw-target');
    $(selector).addClass('active');
  });
});

Now the code works for anything marked as .js-sw. You can change the target selector to whatever you want including multiple selectors (ex. data-sw-target=".sw-target, .someothertarget").