I have this code
<object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>
and jquery
$(".icon-logo").click(function() {
.....
});
but I can't click event.
To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div. to add a div with a class. Then we write: const div = document.
click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
The easiest way to accomplish this goal is to wrap the object tag in a div, bind the click listener to the div, and add pointer-events: none
to the object tag's styles.
Sample fiddle:
.clickable {
background: red;
width: 100px;
height: 100px;
border-radius: 100px;
overflow: hidden;
}
object {
width: 100%;
pointer-events: none;
}
<div class='clickable' onclick='alert("WOW")'>
<object type='image/svg+xml' data='https://douglasduhaime.com/assets/images/icons/home.svg' />
</div>
Concerning the jQuery part, try to use event delegation.
From the docs:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
$(document).on('click', '.icon-logo', function(event) {
document.write('Event type: ' + event.type);
document.write('<br>CSS-Class: ');
document.write($(this).attr('class'));
});
// As said in the docs, you can attach multiple events to multiple selectors.
// A typical example of use may be:
// $(document).on('change blur', '.icon-logo .some-other-class', function() {...}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<object data="images/logo.svg" type="image/svg+xml" class="icon-logo" style="cursor: pointer;">Click me!</object>
Edit after @Kaiido's comment:
<object>
element can't be clicked.One possibility could be to not use an <object>
at all but an <img>
tag instead as suggested in this SO answer: make an html svg object also a clickable link.
This kind of tag <object>
needs some content to show up on the page.
Your tag:
<object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>
is not having any inner HTML-Content, so you won't be able to click it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With