Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mozilla Firefox doesn't load SVG objects in addEventListener('load'

I don't know why, but it works on Chrome and Safari, not in Mozilla. I have object html tag that loads svg file. File contains .s0 classes. I want to handle event when you click on that class.

Who knows what is wrong? sry, jsfiddle does not show object when I tried to paste code there.

<object data="jo.svg" type="image/svg+xml" id="obj"></object>

Code

$(function() {
    var a = document.getElementById('obj');
        a.addEventListener("load", function() {

            // !!!
            console.log('this line is not reachable in Mozilla or reached before svg loaded');

            var svgDoc = a.contentDocument;
            var els = svgDoc.querySelectorAll(".s0");
            for (var i = 0, length = els.length; i < length; i++) {
                els[i].addEventListener("click", function() {
                    alert('clicked');
                }, false);
            }
        });
});
like image 202
sirjay Avatar asked Sep 14 '15 18:09

sirjay


2 Answers

Primarily you need to decide use jquery or not and do not mix jquery-code with native javascript-code.

Javascript version:

<!doctype html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<object data="http://gbip.ru/poselki/genplan/5/full/gp.svg" type="image/svg+xml" id="obj"></object>
<script type="text/javascript">
    window.addEventListener('DOMContentLoaded', function() {
        var obj = document.getElementById('obj');
        obj.addEventListener('load', function(){
            console.log('loaded');
        });
    });
</script>
</body>
</html>

Jquery version

<!doctype html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<object data="http://gbip.ru/poselki/genplan/5/full/gp.svg" type="image/svg+xml" id="obj"></object>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var $obj = $('#obj');
        $obj.on('load', function () {
            console.log('loaded');
        })
    });
</script>
</body>
</html>

Ubuntu 14.04.3 LTS, Firefox 40.0.3

like image 126
cetver Avatar answered Oct 05 '22 12:10

cetver


I solved it by using:

$('#svg').load('"image/svg+xml"', function () {
    alert('svg loaded');
});

It works on Chrome, Firefox and IE9+.

like image 31
naortor Avatar answered Oct 05 '22 13:10

naortor