Search code examples
jquerydry

jQuery - refractoring code (gallery of images)


I have created a gallery of black and white pictures (using the CSS's property filter: grayscale()).

If a user clicks on one of the pictures I would love that picture to display its actual colours.

I have wrote the following code, however, I don't know how to avoid hard coding and create a dry code (so that if I add 50 pictures I do not have to add extra code).

Please help.

$('document').ready(() => {
   $('img').click(() => {
     if ($('img').is("#1")) {
      $('#1').css("filter", "none");
     } else if ($('img').is("#2")) {
       $('#2').css("filter", "none");
     }
etc.

Solution

  • Sounds like you might just need to use a full function and use this instead:

    $('document').ready(() => {
       $('img').click(function() {
        $(this).css('filter', 'none');
      });
    });
    

    If you have images you don't want this listener to activate on, then give all the images you do want the listener to activate on a class, like galleryImg, and then do

    $('.galleryImg')
    

    instead of

    $('img')