Grow your CSS skills. Land your dream job.

What is the best way to reduce this jQuery code?

  • # December 22, 2012 at 4:29 pm

    Hi guys

    I am new to jQuery, and currently have this repetitive code I would like to reduce, however I am not sure what is the best way.

    It is exactly the same, just using different css selectors…

    $(“.product-contain”).find(“a:has(img)”).attr(‘data-fancybox-group’, ‘gallery’).fancybox({
    wrapCSS : ‘fancybox-custom’,
    closeClick : true,

    openEffect : ‘none’,

    helpers : {
    title : {
    type : ‘inside’
    },
    overlay : {
    css : {
    ‘background’ : ‘rgba(238,238,238,0.85)’
    }
    }
    }
    });

    $(“.page-id-31″).find(“a:has(img)”).attr(‘data-fancybox-group’, ‘gallery’).fancybox({
    wrapCSS : ‘fancybox-custom’,
    closeClick : true,

    openEffect : ‘none’,

    helpers : {
    title : {
    type : ‘inside’
    },
    overlay : {
    css : {
    ‘background’ : ‘rgba(238,238,238,0.85)’
    }
    }
    }
    });

    I tried doing it the following way…

    $(“.product-contain, .page-id-31″).find(“a:has(img)”).attr(‘data-fancybox-group’, ‘gallery’).each(function(){
    $(this).fancybox({
    wrapCSS : ‘fancybox-custom’,
    closeClick : true,

    openEffect : ‘none’,

    helpers : {
    title : {
    type : ‘inside’
    },
    overlay : {
    css : {
    ‘background’ : ‘rgba(238,238,238,0.85)’
    }
    }
    }
    });
    });

    …however when I do it this way, the attribute ‘gallery’ does not work (using the fancybox script dynamically). The purpose of the attribute is so users are able to go to the next or previous image while viewing the gallery. Although this attribute appears in the source code, it does not seem to work.

    A link to the page.. http://noteha.co.uk/dev/products/

    I would be grateful for any other suggestions, perhaps the use of variables?

    # December 27, 2012 at 3:36 pm

    You should be able to just state the fancybox once, as you did previously:

      $(".product-contain, .page-id-31").find("a:has(img)").attr('data-fancybox-group', 'gallery').fancybox({
    wrapCSS : 'fancybox-custom',
    closeClick : true,

    openEffect : 'none',

    helpers : {
    title : {
    type : 'inside'
    },
    overlay : {
    css : {
    'background' : 'rgba(238,238,238,0.85)'
    }
    }
    }
    });
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".