1

When i switch to any card i can't select back default card, why?

HTML

<div class="profiles_container">
    <div class="profile_card_selected">
        Default
    </div>
    <div class="profile_card">
        First
    </div>
    <div class="profile_card">
        Second
    </div>
    <div class="profile_card">
        Third
    </div>
</div>

JS

$(".profile_card").click(function(){      
    $('.profiles_container').find(".profile_card_selected").removeClass("profile_card_selected").addClass("profile_card");
    $(this).removeClass("profile_card").addClass("profile_card_selected");
});

https://jsfiddle.net/e7eh5atd/

0

1 Answer 1

1

The problem is that you're only attaching the click event listener to the elements with a class of .profile_card. Since the first element doesn't have a class of .profile_card initially, the click event isn't attached to it.

Without changing any HTML, the easiest way to work around this would be to delegate the click event to a common ancestor so that the class will be checked when the click event is fired (rather than when the event is initially attached like before):

Updated Example

$('.profiles_container').on('click', '.profile_card', function() {
    // ...
});

Alternatively, you could also just attach the event listener to all the children elements regardless of their classes:

Updated Example

$('.profiles_container').children().click(function() {
    // ...
});

However, the better approach would be to use a common class between the elements and then add an .is_selected class in addition to the common class. In doing so, the event listener will be attached to all the elements initially:

Updated Example

$('.profile_card').on('click', function() {
  $('.profile_card').removeClass('is_selected');
  $(this).addClass('is_selected');
});

Updated HTML:

<div class="profiles_container">
  <div class="profile_card is_selected">
    Default
  </div>
  <div class="profile_card">
    First
  </div>

  <!-- ... -->
</div>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.