dougalg
dougalg

Reputation: 564

Mouse pointer hover/jquery click event on SVG embedded in object element not working

I'm using jQuery to dynamically add an element to display an SVG using this code:

someEl = ('#someElement');
cancelButton = $(document.createElement('object')).attr({
            'class': 'cancelButton',
            'id':parent_id+'_xbtn',
            'data': 'img/cancelBtn.svg',
            'type': 'image/svg+xml'
        });
someEl.after(cancelButton);

function cancel() {
    alert('asd');
}
cancelButton.click(cancel);

And I style it to hover with a hand using this CSS:

.cancelButton:hover {
    cursor: hand;
    cursor: pointer;
}

However I found that firstly when I hover the element, the mouse pointer does not change. Hover effects which modify the element itself (e.g. change bg-color) work fine, though. Secondly, the jQuery click handler I attached does not fire either.

Is this some limitation of the <object> element or of how SVG works? Any comments or suggestions appreciated.

Upvotes: 1

Views: 2186

Answers (1)

lakenen
lakenen

Reputation: 3496

In my experience, SVG embedded as <object> elements tend to swallow pointer events (because the browser creates a new document inside the object element, similar to iframe). Is there a reason you can't just use an <img> tag? For example:

someEl = ('#someElement');
cancelButton = $('<img>').attr({
    'class': 'cancelButton',
    'id':parent_id+'_xbtn',
    'src': 'img/cancelBtn.svg'
});
someEl.after(cancelButton);

function cancel() {
    alert('clicked');
}
cancelButton.click(cancel);

Edit:

If you need to use an <object> tag (e.g. because your SVG file references external assets), my solution would be to create a transparent overlay div of same width and height, absolutely positioned over the top of the object, and bind events on that div instead.

Upvotes: 2

Related Questions