Cannot read property 'childNodes' of null in a slider

I have created a simple Javascript slider with Slice and Box effects. It runs and no problem. But when i look up console, I see that after two cycles it throws an error. Browser says that document.getElementById(‘smth’) cannot get specified element. What may be the problem? Below is codepen URL. slider

When i = 6, the identifier is “divn5”

That’s what is causing the problem.

1 Like

i never reach to 6. Cause i created condition that if i greater than pictures length (5), so then it becomes 1

Line 181 is where the typeError occurs, which is the following code:

if(document.getElementById('divin'+(i-1)))
    timer=setInterval(function(){
        pictures.closeIt(document.getElementById('divin'+(i-1)).childNodes, 0)
    },0);

Guess what happens when we add a log inside that setInterval?

if(document.getElementById('divin'+(i-1)))
    timer=setInterval(function(){
        console.log(i, "divin" + (i - 1));
        pictures.closeIt(document.getElementById('divin'+(i-1)).childNodes, 0)
    },0);

We get to see that “Cannot read property ‘childNodes’ of null” occurs when i equals 6.

You may not intend for it to occur, but the code definitely reaches to 6. I suggest that you pull your head out of the sand so that we can investigate why.

Things occur fine on the first loop when i counts from i upwards. It’s at the end of the second loop where the trouble occurs.

I think that the i variable is being reassigned while the setInterval function is taking place.

Using a wrapper function to return the setInterval function allows closure to retain the value of i.

function closePictureClosure(i) {
    return function closePicture() {
        pictures.closeIt(document.getElementById('divin' + (i - 1)).childNodes, 0);
    };
}
timer = setInterval(closePictureClosure(i), 0);

The problem is now fixed.

1 Like

I’ve also cleaned up the JavaScript code so that even JSLint, the harshest critic, is happy with everything.

/*jslint browser */
/*global window */
window.onload = function () {
    "use strict";
    var global = window;
    var pictures = [];
    var timer;
    var timerobj = {};
    var enlik = 700;
    var hun = 306;
    pictures.conf = {
        slices: 10,
        boxes: 9,
        step: 1,
        en: 700,
        boxen: 700 / 3,
        boxhundur: 306 / 3
    };
    pictures.mass = function (anj) {
        var elem;
        if ((anj.nodeType === 1) && (typeof anj.style === "object") && (typeof anj.ownerDocument === "object")) {
            elem = anj;
        } else {
            elem = document.createElement(anj);
        }
        var massEl = {};
        massEl.el = elem;
        massEl.set = function (name, prop) {
            massEl.el.setAttribute(name, prop);
            return massEl;
        };
        massEl.append = function (obj) {
            obj.appendChild(massEl.el);
            return massEl;
        };
        return massEl;
    };
    pictures.closeIt = function (obj, i) {
        var progress = 0.01 * 2;
        if (obj && obj[i] && parseInt(obj[i].style.height) > 0) {
            obj[i].style.height = parseInt(obj[i].style.height) - (parseInt(obj[i].style.height) * progress) + "px";
            obj[i].style.boxSizing = "border-box";
            global.vaxt = setTimeout(function closePicture() {
                pictures.closeIt(obj, i + 1);
            }, 150);
        }
        if (obj && obj[i] && parseInt(obj[i].style.height) <= 0) {
            clearTimeout(global.vaxt);
            obj[i].style.height = "306px";
            obj[i].style.visibility = "hidden";
            obj[i].style.borderRight = "0px solid #c0c0c0";
        }

    };
    pictures.addEvent = function addEvent(target, functionref, tasktype) {
        if (target.addEventListener) {
            target.addEventListener(tasktype, functionref, false);
        } else if (target.attachEvent) {
            target.attachEvent("on" + tasktype, function handler() {
                return functionref.call(target, window.event);
            });
        }
    };
    pictures.getId = function (obj) {
        if (obj.split(" ").length > 1) {
            var res = obj.split(" ");
            return document.getElementById(res[0]).getElementsByTagName(res[1]);
        } else {
            return document.getElementById(obj);
        }

    };
    var i = 0;
    var en;
    var uzun;
    var ad;
    var el;
    while (i < pictures.getId("slider a").length) {
        en = pictures.getId("slider a")[i].childNodes[0].width;
        uzun = pictures.getId("slider a")[i].childNodes[0].height;
        ad = pictures.getId("slider a")[i].childNodes[0].src;
        pictures.push(pictures.getId("slider a")[i].childNodes[0].src);
        el = pictures.mass("div").set("id", "divin" + i).set("style", "width:" + en + "px;height:" + uzun + "px; background:url(" + ad + ")");
        pictures.getId("slider a")[i].appendChild(el.el);
        i += 1;
    }
    pictures.sliceIt = function sliceIt(i) {
        var j;
        var ad2;
        clearTimeout(timer);
        if (i > pictures.length) {
            pictures.getId("slider a")[i - 2].style.display = "none";
            pictures.getId("divin" + (i - 2)).innerHTML = "";
            i = 1;
            j = 0;
            pictures.getId("slider a")[j].style.display = "block";
        } else {
            j = i - 1;
        }

        ad = pictures[i];
        if (i > 4) {
            ad = pictures[0];
        }
        if ((i - 1) !== 0) {
            pictures.getId("slider a")[j - 1].style.display = "none";
            pictures.getId("divin" + (j - 1)).innerHTML = "";
            pictures.getId("slider a")[j].style.display = "block";
        }
        pictures.mass(pictures.getId("divin" + (i - 1))).set("style", "width:" + en + "px;height:" + uzun + "px; background:url(" + ad + ")");
        var anadiv = pictures.getId("divin" + (i - 1));
        enlik = 700;
        ad2 = pictures[(i - 1)];
        var n = 0;
        var d = 0;
        while (n < pictures.conf.slices) {
            pictures.mass("div")
                .set("id", "divs" + (i) + n)
                .set("style", "display:inline-block;vertical-align:bottom; float:left;overflow:hidden;width:" + enlik / pictures.conf.slices + "px;height:" + uzun + "px; background:url(" + ad2 + ");background-position: " + (-d) + "px 0px; background-repeat:no-repat")
                .append(anadiv);
            n += 1;
            d = (enlik / pictures.conf.slices) * n;
        }
        function closePictureClosure(i) {
            return function closePicture() {
                pictures.closeIt(document.getElementById("divin" + (i - 1)).childNodes, 0);
            };
        }
        if (document.getElementById("divin" + (i - 1))) {
            timer = setInterval(closePictureClosure(i), 0);
        }
        global.timermain = setTimeout(function () {
            i += 1;
            pictures.noxIt(i);
        }, 6000);
    };

    /*burda baslayir */
    pictures.closeIts = function closeIts(obj, i, z) {
        var opac;
        var progress = 0.01 * 3;

        if (obj[i] && parseInt(obj[i].style.height) <= 0) {
            clearInterval(timerobj["timer" + z]);
            clearTimeout(global.vaxt);
            obj[i].style.borderRight = "0px solid #c0c0c0";
        }
        if (obj && obj[i] && parseInt(obj[i].style.height) > 0) {
            if (obj && obj[i]) {
                opac = 0.8 - ((306 / 5) - parseInt(obj[i].style.height)) / (306 / 5) + 0.3;
            }
            if (parseInt(obj[i].style.height) - 2 < 0) {
                obj[i].style.height = "0px";
                obj[i].style.width = "0px";
            } else {
                obj[i].style.height = parseInt(obj[i].style.height) - (parseInt(obj[i].style.height) * progress) + "px";
                obj[i].style.opacity = opac;
            }
            obj[i].style.width = parseInt(obj[i].style.width) - (1 * 3) + "px";
            obj[i].style.boxSizing = "border-box";
            global.vaxt = setTimeout(function closePicture() {
                pictures.closeIts(obj, i + 1, z);
            }, 150);
        }

    };
    /* burdaq qurtarrir */

    pictures.noxIt = function noxIt(i) {
        var j;
        var ad2;
        var enn;
        var n = 1;
        var x;
        while (n <= 5) {
            clearInterval(timerobj["timer" + n]);
            n += 1;
        }
        if (i > pictures.length) {
            pictures.getId("slider a")[i - 2].style.display = "none";
            pictures.getId("divin" + (i - 2)).innerHTML = "";
            i = 1;
            j = 0;
            pictures.getId("slider a")[j].style.display = "block";
        } else {
            j = i - 1;
        }
        ad = pictures[i];
        if (i > 4) {
            ad = pictures[0];
        }
        if ((i - 1) !== 0) {
            pictures.getId("slider a")[j - 1].style.display = "none";
            pictures.getId("divin" + (j - 1)).innerHTML = "";
            pictures.getId("slider a")[j].style.display = "block";
        }
        pictures.getId("divin" + (j)).innerHTML = "";
        ad2 = pictures[(i - 1)];
        pictures.mass(pictures.getId("divin" + (i - 1))).set("style", "width:" + en + "px;height:" + uzun + "px; background:url(" + ad + ")");
        hun = 306 / 5;
        enn = 700 / 8;
        x = 1;
        var anadiv = pictures.getId("divin" + (i - 1));
        var z;
        var y;
        var os;
        while (x <= 5) {
            z = -(hun * (x - 1));
            y = 1;
            pictures.mass("div").set("id", "maindiv" + x).set("style", "position:absolute;top:" + (-z) + "px; left: 0px").append(anadiv);
            while (y <= 8) {
                os = enn * (y - 1);
                pictures.mass("div").set("id", "divsn" + x + y).set("style", "width:" + enlik / 8 + "px;height:" + hun + "px; background:url(" + ad2 + ");background-position: " + (-os) + "px " + z + "px;position:absolute;top:0px; left: " + os + "px").append(pictures.getId("maindiv" + x));
                y += 1;
            }
            x += 1;
        }
        n = 1;
        function setTimer(z) {
            timerobj["timer" + z] = setInterval(function () {
                if (pictures.getId("maindiv" + z)) {
                    pictures.closeIts(document.getElementById("maindiv" + z).childNodes, 0, z);
                }
            }, (z - 1) * 12);
        }
        while (n <= pictures.length) {
            setTimer(n);
            n += 1;

        }
        global.timermain = setTimeout(function () {
            i += 1;
            pictures.sliceIt(i);
        }, 6000);
    };
    pictures.noxIt(pictures.conf.step);
};

This gives a good base from which to proceed with further cleaning;

1 Like

Thank you very very much for attention. You solved not only my problem, but also forwarded me to the right way. As you said this a good base for me to proceed further programming. Very cool.:blush:
Thanks again for spending time!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.