0

Basically I am adding a class of "id" when a <div> is clicked. The ID is updated to "active"

http://mpagallery.co.uk/exibitions/future/

If you click on the small image, the builder-gallery-item <div> needs to add a id="active" to the end.

Here is what I have tried in my fiddle, and have exactly the same code in an external file, but it just won't work.

jQuery(function ($) {
  $(document).ready(function ($) {
    $('.builder-gallery-item').on('click', changeClass);
  });
});

function changeClass() {
  $('.builder-gallery-item').removeAttr('id', 'active');
  $(this).attr('id', 'active');
}
12
  • 3
    You have a document ready inside a document ready. Unnecessary. Commented Aug 21, 2014 at 20:13
  • 2
    Tip: Manipulate classes, not IDs. Commented Aug 21, 2014 at 20:13
  • 1
    .removeAttr() expects one parameter, which is the attribute you want to remove. Commented Aug 21, 2014 at 20:14
  • j08691 - I have removed the document ready now, it still does not work. Commented Aug 21, 2014 at 20:19
  • MelanciaUK - I am trying to change the ID as I already have classes there which need to be kept in there Commented Aug 21, 2014 at 20:20

1 Answer 1

2

I think you're looking for the addClass and removeClass methods

After reading your comment, I would strong encourage you to use classes rather than IDs, because HTML Id elements should be unique

   $(document).ready(function () {
       $(".builder-gallery-item").on("click", function () {
          $('.builder-gallery-item').removeClass('active');
          $(this).addClass('active');
        });
    });

See this JsFiddle

Edit To clean up the comments, the OP has an updated JsFiddle, where the active class is still not being applied to the divs that contain pictures.

Based on that JsFiddle, you are calling addClass('active') on all of the elements with the builder-gallery-item class rather than just the one that was clicked. You should be using:

jQuery(function ($) {
    $(".builder-gallery-image").on("click", function () {
        $('.builder-gallery-item').removeClass('active');
        $(this).closest('div').addClass('active');
    });
});

$(this) was actually referencing the figure object, which is why I used the $(this).closest('div') instead. See the Updated Fiddle

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

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.