Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to listen image load event in SVG?

Is it possible to listen for an <image> load event in SVG? If yes, how to do this?

like image 692
Rustam Avatar asked Jul 09 '12 07:07

Rustam


People also ask

Can we attach event handlers to SVG?

SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.

What is SVG load?

The load event fires on an SVGElement when it is loaded in the browser, e.g. in the DOM in the case of an embedded <svg> . It is basically the same as the standard load DOM event.

Can SVG include image?

<image> The <image> SVG element includes images inside SVG documents. It can display raster image files or other SVG files. The only image formats SVG software must support are JPEG, PNG, and other SVG files.

Which event occurs when page or image is loaded?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).


2 Answers

Yes it's possible.

In markup:

<image xlink:href="example.png" width="10" height="10" 
       onload="alert('loaded')"/>

See jsfiddle.

In script:

<script>
  var img = document.createElementNS("http://www.w3.org/2000/svg", "image");
  img.addEventListener('load', function() { alert('loaded'); });
  // or alternatively:
  // img.onload = function() { alert('loaded'); }
  img.width.baseVal.value = 100;
  img.height.baseVal.value = 100;
  img.href.baseVal = "example.png";
</script>

See jsfiddle.

like image 181
Erik Dahlström Avatar answered Oct 18 '22 00:10

Erik Dahlström


I found that this would not work for SVG object created using D3, but the answer here worked great:

How can I display a placeholder image in my SVG until the real image is loaded?

For example this worked:

var img = innerG.append("image")
    .attr('onload', function() {
        console.log('loaded');
    })
    .attr("xlink:href", src)
    .attr("width", size)
    .attr("height", size);

But this did not work:

var img = innerG.append("image")
    .attr("xlink:href", src)
    .attr("width", size)
    .attr("height", size);

img.addEventListener('load', function() { console.log('loaded'); });
like image 44
zayquan Avatar answered Oct 17 '22 23:10

zayquan