简体   繁体   中英

jQuery | Add/Remove Class on Click | Best Practise

today I had to set a number of images as a galery. On the mobile version of this site I had to stack the images because it wasn´t possible to show them in a row of 4 or something.

Yet the images were quite high (350px) for a mobile view so I´ve decided to shrink them down to a height of 100px and make them clickable to extend to their full height.

I did this just by adding or removing a class called "extended" which would set the height to 350px again.

The JavaScript I used for this works but yet I´m not sure if this is what you would call best practise or if it could be done easier:

$('.galery__img--fragrance').on('click', function() {
    if($(this).hasClass('extended')) {
      $(this).removeClass('extended');
    } else {
      $(this).parent().find('.extended').removeClass('extended');
      $(this).addClass('extended');
    }
  });

I hope this question isn´t to redundant but I´m quite new to JS/jQuery and I want to do it right :-)

Edit: Maybe I should´ve mentioned that I wanted to make images collapse to a height of 100px if they were clicked again or if another image was clicked

Use .toggleClass() function to add/remove class simultanuously:

$('.galery__img--fragrance').on('click', function() {
    $(this).toggleClass('extended');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM