Luciano Luciano - 1 month ago 13
HTML Question

Cannot correct load external js file

I have a JS file for dynamic tooltips, if I use the codes with

script
tag in the html page it works. But when I use the
script src
tag to use it from a source, the script loads but when I try with the tooltips works, they don't work. This is the JS code

var tooltips = document.querySelectorAll('.tooltip div');

window.onmousemove = function (e) {
var x = (e.clientX + 20) + 'px',
y = (e.clientY + 20) + 'px';
for (var i = 0; i < tooltips.length; i++) {
tooltips[i].style.top = y;
tooltips[i].style.left = x;
}
};

Answer

Run this script only when your HTML is rendered.

window.onload = function() {
    var tooltips = document.querySelectorAll('.tooltip div');

    window.onmousemove = function (e) {
        var x = (e.clientX + 20) + 'px',
            y = (e.clientY + 20) + 'px';
        for (var i = 0; i < tooltips.length; i++) {
            tooltips[i].style.top = y;
            tooltips[i].style.left = x;
        }
    };
}
Comments