Jquery: Returning Value From Trigger
What you can do is use .triggerHandler()
instead of .trigger()
. This will return a value.
var user_id=$("#my_div").triggerHandler("get_id", [username]);
You cannot return a value from a trigger, but you can store information in many different ways, one way is using a object as a parameter:
//event
$("element").on("click", function(event, informationObj) {
informationObj.userId = 2; //you have to access a propery so you can modify the original object
});
//trigger
var informationObj = {userId : 0};
$("element").trigger("click", [informationObj ]); //informationObj.userId === 2
other way is using jQuerys .data()
method
//event
$("element").on("click", function() {
$(this).data("userId", 2);
});
//trigger
$("element").trigger("click").data("userId") //2
Another thing you can do is modifying a variable that's declared outside the event and then using it after calling the trigger, or storing it as a property in the element that has the event with the this
keyword like this:
//inside the event function
this.userId = 2;
//outside the event
$("element").trigger("click").get(0).userId
Hope it helps.
Edit:
Also, take a look at @Arm0geddon answer below, using .triggerHandler()
, just beware that it has some side effects, like not bubbling up the DOM hierarchy.
The trigger
function doesn't return the value you return from the event handler.
It returns jQuery object
...
.trigger( eventType [, extraParameters] ) Returns: jQuery
docs
This was designed so you could write things like this:
$("#my_div").trigger("get_id", [username]).val('foo').css('color', 'red');
A trigger cannot return a response, because it's a callback method.
In addition jQuery have a fluid API, so .trigger()
returns always $(this)
.
You can write $("#my_id").trigger(something).show().on(someelse)...