javascriptdom-eventsoneclick

Condensing multiple onclicks into one


This is my current code:

document.getElementsByName('links')[0].onclick = function (event) {
event = event || window.event;
var target = event.target || event.srcElement,
    link = target.src ? target.parentNode : target,
    options = {index: link, event: event},
    links = this.getElementsByTagName('a');
blueimp.Gallery(links, options);
};

document.getElementsByName('links')[1].onclick = function (event) {
event = event || window.event;
var target = event.target || event.srcElement,
    link = target.src ? target.parentNode : target,
    options = {index: link, event: event},
    links = this.getElementsByTagName('a');
blueimp.Gallery(links, options);
};

I realize that this copy and pasting is terribly inefficient (and would only get worse when I need to add [2].onclick, [3].onclick, etc.), so is there a way I could condense all of them together?

I'm a beginner when it comes to Javascript, so please forgive me if this question is extremely simple.


Solution

  • jQuery aside, all you need to do is encapsulate the duplicated code, e.g:

    <script>
    var elements = document.getElementsByName('links');
    Array.prototype.forEach.call(elements, function (el) {
        el.onclick = function (event) {
            event = event || window.event;
            var target = event.target || event.srcElement,
                link = target.src ? target.parentNode : target,
                options = {index: link, event: event},
                links = this.getElementsByTagName('a');
            blueimp.Gallery(links, options);
        };
    });
    </script>