Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Events does not work on html5 object tag

It seems that trigger/on jquery events both standard and custom do not work on 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:

  1. Am I only one who has this bug or am I doing something wrong?
  2. Is this a jQuery bug or is it expected behaviour?
  3. Any workarounds (especially for custom events besides using another element)?
like image 448
Pavel Gurecki Avatar asked Dec 05 '14 11:12

Pavel Gurecki


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 could use alternative JQuery functions to add the element.

like image 147
Fintan Kearney Avatar answered Oct 26 '22 14:10

Fintan Kearney


Update:
First Post was completely wrong however this seems to work for clicking on the 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 relevant code to the issue 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> 
like image 38
Adam Forbis Avatar answered Oct 26 '22 15:10

Adam Forbis