After several hours of trying to figure this out and reading documentation, I'll surrender on this one. I come from a C/C++ background trying to learn Javascript and I'm getting a little confused on what the difference is between a DOM element and an Object. I thought I understood but when I call certain functions on Objects, like ".addEventListener()" I get the famous "Undefined is not a function" error, amongst other funny things. So here's two attempts at the same thing using SVG.js. I'm basically just trying to add an event listener to every shape that I've generated inside of my SVG canvas thus far, such that when any shape is clicked it will change color independent of all others.
One gives me "Undefined..." on the add event listener line, which I solved with the second version but now I'm getting the "Undefined..." error on the only declaration inside of my function.
Could you clarify what the difference is between a DOM element and an Object and then help me understand why the "Undefined is not a function" error is popping up in my second example? Thanks.
Version 1: canvas.get() returns an object, one of the shapes I've generated, error appears on .addEventListener() call
function changeColor(e) {
this.fill({color: currentColor});
}
//add event listeners for every element of SVG
var it;
for (it=3; it<=18; it++){
var canvasName = canvas.get(it);
canvasName.addEventListener("click", changeColor);
}
Version 2: the event listener is now being added to a DOM element and the "Undefined is not a function" error appears in declaration inside of function (line 2)
function changeColor(e) {
this.fill({color: currentColor});
}
//add event listeners for every element of SVG
var it;
for (it=3; it<=18; it++){
//get string to search for id in DOM
var idName = "SvgjsRect" + (1006+it);
var box = document.getElementById(idName);
box.addEventListener("click", changeColor);
}
My final version. I realized that they basically abandon all native DOM functions for their own, so I used their event binding methods.
var changeColor = function() {
this.fill({color: currentColor});
}
//add event listeners for every element of SVG
var it;
for (it=3; it<=18; it++){
var box = canvas.get(it);
box.on('click', changeColor);
}