1

I have the folowing example:

<div class="filtrer">
    <a class="bold">Url 1</a>
    <a>Url 2</a>
</div>

First url is active, second is inactive, bold means is selected. I should be allowed to press only on Url 2, and as soon as i do that, the bold class shoud switch to the Url 2.

What i already tryed and did not work was this:

$('.filtrer a').filter(':not(.bold)').on('click', function(){
    var current = $('.filtrer a').filter(':not(.bold)');
    var standby = $('.filtrer a.bold');

    current.addClass('bold');
    standby.removeClass('bold');
})

Does anybody know why this is not working? Or have an optimized solution? Thanks

3
  • 1
    Does it work if you change $('.filtrer a') to $('.filter a')? Commented Nov 14, 2013 at 15:56
  • Sory, i corrected that spelling mistake. Commented Nov 14, 2013 at 15:59
  • What about the single quote / double quote on your bold anchor? Commented Nov 14, 2013 at 16:02

5 Answers 5

5

You are dealing with dynamic element selectors, so you need to use delegation based event handlers

var $as = $('.filter a');
$('.filter').on('click', 'a:not(.bold)', function () {
    var current = $as.filter(':not(.bold)');
    var standby = $as.filter('.bold');

    current.addClass('bold');
    standby.removeClass('bold');
})

Demo: Fiddle

It can be written as

var $as = $('.filter a');
$('.filter').on('click', 'a:not(.bold)', function () {
    $as.toggleClass('bold');
})

Demo: Fiddle

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

2 Comments

+1 on the second solution, the first one is pointless and too much code.
@Phil that was to correct the OP's code.... and was the first solution before I cleaned it up.... so kept it there
1
$('.filter').on('click','a:not(.bold)',function(){
  $(this).siblings().add(this).toggleClass('bold');
});

Or without jQuery:

<div class="filter">
  <input type="radio" name="url" id="url1"><label for="url1">url1</label>
  <input type="radio" name="url" id="url2"><label for="url2">url2</label>
</div>

.filter input[type=radio]{
  display:none;
}
.filter input[type=radio]:checked + label{
  font-weight:bold;
}

Example 1 Example 2

Comments

0

You misspelled "filter", change it in your code or the HTML.

Comments

0
$('.filtrer').on('click',' a:not(.bold)', function(){    
    $('.filtrer a.bold').removeClass('bold');;
    $(this).addClass('bold');    
})

Comments

0

Something like :

$('.filter a').click(function() {
    $('.filter a').removeClass('bold');
    $(this).addClass('bold');
});

?

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.