Uncaught TypeError: undefined has no properties

Who can help with the question? Called when trying to open an image

The error is in this line of code

: srcset[srcset.length – 1])[0];

thanks

$(document).on('click', '.fancy-srcset', function (e) {
        e.preventDefault();
        var fancyGroup = e.currentTarget.dataset.fancyboxGroup;
        var fancyElements = !fancyGroup
            ? [].slice.call(e.currentTarget.parentElement.children)
            : [].slice.call(e.currentTarget.parentElement.parentElement.querySelectorAll('[data-fancybox-group="' + fancyGroup + '"]'));
        var size = '400';
        ['576', '768', '992', '1200'].every(function (screenSize) {
            if (window.matchMedia('(min-width: ' + screenSize + 'px)').matches) {
                size = screenSize;
                return true;
            }
            return false;
        });
        $.fancybox(
            fancyElements.map(function (fancyElement) {
                var srcset = fancyElement.dataset.srcset.split(', ').map(function (elem) {
                    return elem.split(' ');
                });
                return (size
                    ? srcset.find(function (elem) {
                        return elem[1] === size + 'w';
                    })
                    : srcset[srcset.length - 1])[0];
            }),
            {
                index: fancyElements.indexOf(e.currentTarget)
            }
        );
    });

enter image description here

36 thoughts on “Uncaught TypeError: undefined has no properties”

  1. srcset is most likely undefined at some point. So consider initializing it to an empty array when that happens. Like this.

    var srcset = fancyElement
                   .dataset.srcset.split(', ')
                   .map(function (elem) {
                        return elem.split(' ');
                    }) || [];
    
    Reply

Leave a Comment