brettinternet
brettinternet

Reputation: 575

Can using an SVG from <object> allow click events to propagate to parent handlers?

Adding an SVG from an HTML <object> appears to create an unresponsive space where click events are not propagated through the SVG and object elements.

In the example, this is demonstrated by clicking in the center of the button. The click action doesn't appear to propagate the event to the parent element, the button. However, when the edge of the button is clicked (away from the SVG), the click event is invoked.

var buttonEl = document.getElementById('button');
buttonEl.addEventListener('click', function() {
  console.log('Clicked!')
})
<button id="button" style="padding:5rem;">
  <object data="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/check.svg" type="image/svg+xml" style="height:40px;width:40px;">
    Check
  </object>
</button>

Upvotes: 2

Views: 1466

Answers (2)

Besworks
Besworks

Reputation: 4483

@brettinternet's answer won't help if you have hover styles or other such interactivity that you need to maintain inside the SVG. I figured out that the proper way to handle this is to attach your click listeners to the contentDocument of the <object> element but you have to wait until the external document is loaded before doing this.

let yourObject = document.querySelector('object#objid');
yourObject.addEventListener('load', event => { 
    yourObject.contentDocument.addEventListener('click', event => 
        console.log(event));
    });
});

Upvotes: 2

brettinternet
brettinternet

Reputation: 575

Use pointer-events:none; on the object element.

var buttonEl = document.getElementById('button');
buttonEl.addEventListener('click', function() {
  console.log('Clicked!')
})
<button id="button" style="padding:5rem;">
  <object style="pointer-events:none;height:40px;width:40px;" data="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/check.svg" type="image/svg+xml">
    Check
  </object>
</button>

Upvotes: 5

Related Questions