Search code examples
javascriptjqueryoptimizationlightgallery

How do I optimize the code so that I don't have to write a new number every time?


I have js code like this:

 lightGallery($("#web1")[0], {
    selector: 'this',
    mobileSettings: {
        controls: false,
        showCloseIcon: true,
        download: false,
    }
});
lightGallery($("#web2")[0], {
    selector: 'this',
    mobileSettings: {
        controls: false,
        showCloseIcon: true,
        download: true,
    }
});
lightGallery($("#web3")[0], {
    selector: 'this',
    mobileSettings: {
        controls: false,
        showCloseIcon: true,
        download: true,
    }
});

How do I optimize the code so that I don't have to write a new number every time?


Solution

  • Consider the following.

    $("[id^='web']").each(function(i, el){
      lightGallery($(el)[0], {
        selector: 'this',
        mobileSettings: {
          controls: false,
          showCloseIcon: true,
          download: false,
        }
      });
    });
    

    This will go over each one that has an ID that starts web and apply the same code.