boisvert boisvert - 3 months ago 10
jQuery Question

jquery return of trigger

I am using JQuery to attach a function to an element:

$("button").on("random",
function() {


but I want the function to return a result:

alert('called');
return 'button has been clicked';
}


The problem is, when I used 'trigger' to trigger the function, the function executes, but the result isn't returned - the JQuery element (I think) is returned instead.

$("a").on("click",
function() {alert($('button').trigger('random'));}
)


How do I write or call the function so that its result is returned?

JSFiddle: https://jsfiddle.net/cs3cqv3z/3

Thank you.

Answer

You cannot return a value to a trigger but you can store its value. One way is to pass an object to the call and storing value in it.

$(document).ready(function() {
    $("button").on("random",
                   function(e, obj) {
                     alert('called');
                     obj.value= 'button has been clicked';
                   }
                  );
    $("a").on("click",
              function()
              {
var infoObj = {value: ''};               $('button').trigger('random',[infoObj]);
console.log(infoObj.value)}
             )
  }
)

JSFIDDLE

Another way is using jQuery's `.data()` method.

$(document).ready(function() {
    $("button").on("random",
                   function(e, obj) {
                     alert('called');
                     obj.value= 'button has been clicked';
                   }
                  );
    $("a").on("click",
              function()
              {
var infoObj = {value: ''};               $('button').trigger('random');
alert(infoObj.value)}
             )
  }
)

JSFIDDLE

Another method is to use the .triggerHandler() instead of the .trigger(). However I would suggest you to go through the docs first and see if it fits your requirement. It does solve the problem though.

$(document).ready(function() {
    $("button").on("random",
          function(e) {
               alert('called');
              return 'button has been clicked';
          }
     );
    $("a").on("click", function() {             
                alert($('button').triggerHandler('random'));
        })
})

JSFIDDLE