Pavel Gurecki
Pavel Gurecki

Reputation: 1209

Events 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)?

Upvotes: 7

Views: 2450

Answers (2)

Adam Forbis
Adam Forbis

Reputation: 461

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> 

Upvotes: 1

Fintan Kearney
Fintan Kearney

Reputation: 764

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.

Upvotes: 1

Related Questions