Skip to content

How can I attach some data for jQuery event for bubbling?

The easiest way to show what I’m trying to achieve is to make a simple example:

$("#button-1").click(function (e) { e.data = { flag: true } });
$("#button-2").click(function (e) { e.data = { flag: false } });

$(window).click(function (e) { $("p").html(JSON.stringify(e.data)) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id='button-1'>button 1</button>
<button id='button-2'>button 2</button>

<p></p>

When I attach anything to an event, it gets disappeared after bubbling up to the window. Is there any way to keep it?

Answer

I can’t tell you right now why it won’t work that way, I need to first check the source of jQuery.

But you could attach it to the originalEvent. But I would probably use a more specific name then data, to avoid naming conflicts.

$("#button-1").click(function (e) { e.originalEvent.data = { flag: true } });
$("#button-2").click(function (e) { e.originalEvent.data = { flag: false } });

$(window).click(function (e) { $("p").html(JSON.stringify(e.originalEvent.data)) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id='button-1'>button 1</button>
<button id='button-2'>button 2</button>

<p></p>