JayWayze
JayWayze

Reputation: 168

Can't add events to inline SVG elements

I'm trying to access inline SVG elements in JavaScript, to add a click event. I'm running into issues adding the event to anything else than a single element identified with id. Using document.getElementById("p1_1_1") will work, but I'll need to manipulate 200 rectangles, so I will need to use document.getElementsByTagName or document.getElementsByClassName - both of which return meaningful HTMLCollections, but the addEvent won't add the event.

I've tried Firefox 17 and Chrome 23, and some additional methods, such as the getElementsByTagNameNS, bu no luck so far.

Thankful for any help you can offer.

Here are stripped down versions of the JS code and HTML/SVG I'm working with:

JavaScript:

 function testing() {
    var testDiv = document.getElementById("tester");
    testDiv.innerHTML = '<h1>Success!</h1><br>';
}

function addEvent(obj, evt, func) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, func, false)
    } else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, func);
    } else {
        alert("no success adding event");
    }
}

function init() {
    var targetSquares = document.getElementsByTagName("rect");
    addEvent(targetSquares, "click", testing);
}

window.addEvent(window, "load", init);

inline SVG

<!DOCTYPE html>
<html lang="en-GB">
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="bsroyale.js"></script>
    </head>
    <body>
<div id="tester">
</div>
        <div id="gamemap">
              <svg xmlns="http://www.w3.org/2000/svg"
                   xmlns:xlink="http://www.w3.org/1999/xlink"
                   viewBox="0 0 600 600">
                <rect x="50" y="50" width="20" height="20" class="p1" id="p1_1_1" />
                <rect x="71" y="50" width="20" height="20" class="p1" id="p1_2_1" />
                <rect x="92" y="50" width="20" height="20" class="p1" id="p1_3_1" />
                <rect x="113" y="50" width="20" height="20" class="p1" id="p1_4_1" />
                <rect x="134" y="50" width="20" height="20" class="p1" id="p1_5_1" />
                <!-- etc etc, 200 rect in total-->
            </svg>
        </div>
    </body>
</html>

Upvotes: 4

Views: 916

Answers (1)

Chris
Chris

Reputation: 769

document.getElementsByTagName("rect") returns an HTML collection. You must then loop through this collection (i.e. for each...) and add the event listeners to each collection-item.

I didn't test it, but your init function could look like this:

function init() {
    var targetSquares = document.getElementsByTagName("rect");
    for (var i = 0; i < targetSquares.length; i++) {
        addEvent(targetSquares[i], "click", testing);
    }
}

Upvotes: 2

Related Questions