Events do not work on html5 object tag

It seems that jquery trigger / events, both standard and custom, do not work with an object tag.

This does not work :

var $test = $("<object>"); $test.on("test", function (){ console.log("jquery test handler"); }); $test.trigger("test"); 

While it works with other html tags (tried div, video, etc.).

Vanilla js solution works:

 var test = document.createElement("object"); test.addEventListener("testV", function(e) { console.log("vanilla test handler"); }); var event = new CustomEvent("testV"); test.dispatchEvent(event); 

jQuery ver. 1.11.1
Tests: http://codepen.io/anon/pen/dPGoJg


Questions

  • Am I the only one who has this error, or am I doing something wrong?
  • Is this a jQuery bug or is this the expected behavior?
  • Any workarounds (especially for custom events other than using another element)?
+6
source share
2 answers

Your first example does not work, because the element has not yet been added to the DOM.

 var $test = $("body").append("<object>"); $test.on("test", function (){ console.log("jquery test handler"); }); $test.trigger("test"); 

You can use alternative jQuery functions to add an element.

+1
source

Update:
The first post was completely wrong, however it seems to work to click on an object tag

 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script> $(document).on('click', 'object', function(event) { console.log("jquery test handler");}); </script> <object width="400" height="400">Object</object> 

The important part is $(document)
Update 2: More Important Issue Code Using Trigger and Custom Event

 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <object>Object</object> <script> $(document).on('test', 'object', function(event) { console.log("jquery test handler");}); $('object').trigger('test'); </script> 
0
source

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


All Articles