Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen for jQuery Event With Vanilla JS

Tags:

So I am trying to determine whether its possible to listen for events added with jQuery using vanilla JS. I found this question:

Listen to jQuery event without jQuery

which definitely answers it for version 1 of jQuery. How about version 3 however?

I have a fiddle that I have put together to test out, but I am unable to get the 1st submit to work with any version of jQuery. Am I missing something, or is the event model in jQuery 3 still not using the DOM event model?

https://jsfiddle.net/ydej5qer/1/

Here is the code in the fiddle:

HTML:

<div id="div1">
<p>
This is div1. My event was added via jQuery and is listened for by vanilla JS.
</p>
<p>
  Enter the number 2 to have the event fired.
</p>
<input type="text" id="input1" />
<button id="button1">
Submit
</button>
</div>
<div id="div2">
  <p>
    This is div2. My event was added via vanilla JS and is listened for by jQuery.
  </p>
  <p>
    Enter the number 2 to have the event fired.
  </p>
  <input type="text" id="input2" />
  <button id="button2">
  Submit
  </button>
</div>

JavaScript:

var $input1 = $("#input1");
var $input2 = $("#input2");
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");

var event1 = "event1";
var event2 = "event2";

$("#button1").click(function() {
    if (+$input1.val() == 2) {
    $input1.trigger(event1, {message: "Event 1 triggered!"});
  }
});

input1.addEventListener(event1, function(e) {
    console.log("Event 1 triggered! message=" + e.detail.message);
});

$("#button2").click(function() {
    if (+$input2.val() == 2) {
    var event = new CustomEvent(event2, {detail: {message: "Event 2 triggered!"}});
    input2.dispatchEvent(event);
  }
});

$input2.on(event2, function(e) {
    console.log("Event 2 fired, but I don't know how to get the message!");
});
like image 866
thatidiotguy Avatar asked Dec 01 '16 16:12

thatidiotguy


1 Answers

The short answer is that this is impossible as jQuery provides an event layer over vanilla JS. That means that vanilla JS cannot talk to that added layer.

So in summary, jQuery can catch vanilla JS events, but vanilla JS cannot catch jQuery added events.

like image 99
thatidiotguy Avatar answered Oct 03 '22 13:10

thatidiotguy