Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Other What is the best way to reduce this jQuery code?

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #41537
    croydon86
    Participant

    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?

    #119144
    tylerhq
    Member

    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)
  • The forum ‘Other’ is closed to new topics and replies.