How to associate a click event with an object tag?

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 not click the event.

+7
source share
2 answers

1. Problem: event handling

As for the jQuery part, try using event delegation.

From 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 comment:

2. Error: the <object> element cannot be pressed.

One possibility might be to use <object> instead of the <img> tag instead of <object> <img> , as suggested in this SO answer: make the html svg object also linkable .


<beat> 2. Error: empty HTML tag

For this type of <object> you need to display the content on the page.

Your tag:

<object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>

has no internal HTML content, so you won’t be able to click it.

+12
source

The easiest way to achieve this goal is to wrap the object tag in a div element, attach a click listener to the div element and add pointer-events: none from the styles of the object tag.

Sample violin:

 .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> 
+2
source

Source: https://habr.com/ru/post/975490/


All Articles