0

Can I get value from jquery event function?

I want to get something like this:

function Init() {
    var my_variable = $some_object.click(function() {
         var my_variable = 'value';
         return my_variable // I need to get the variable value from click event
                            // but I don't know ways to do it
    });

    console.log(my_variable); // I want to have possibility to use the value here
}
3
  • 1
    You can't return anything from an event handler. If you want to see the value, put the console.log inside the handler. Commented Jan 9, 2015 at 11:44
  • 1
    Your Init() function will be long gone before anyone clicks $some_object. How would you envision this working? Commented Jan 9, 2015 at 11:47
  • There are patterns to using values from event handlers. You need to explain the overall aim of your code to get a good answer. The answer by Mister Epic is not a practical way of using values outside the handler and should not be followed. Commented Jan 9, 2015 at 12:13

4 Answers 4

1

No.

The function that sets the event handler will have finished running before the event handler runs.

Sign up to request clarification or add additional context in comments.

1 Comment

Short and to the point. A positive example of how to do it would have been nice as this is more a comment than an answer +1 anyway.
1

No, you can't do that. You can only capture the value in a variable defined outside the scope of your handler:

function Init() {
    var my_variable = '';

    $some_object.click(function() {
         my_variable = 'value';
    });

    console.log(my_variable); //Prints empty string

    $some_object.trigger('click');

    console.log(my_variable); //Prints 'value'
}

1 Comment

This example implies it is a valid way to use the value outside of the event. That is not the case. You need to add more explanation that the correct way to use the value is only inside the event handler.
0

The answer to your question is No!. You cannot return a value from event handler. Now next thing which made you curious is how to get some data which comes from the event handler itself. This is where event propagation comes and passing some data along with that.

Checkout below fiddle which shows how data which was created in event handler of button click, is being passed for any custom purpose.

http://jsfiddle.net/kowmwq9j/

Below is simple html and understandable javascript code

<div id='parent'>
    <button id='test'>CLick</button>
</div>

var a=document.getElementById('test');
a.addEventListener('click', function(){
   var str='sample';
   //creating a custom event with name 'build' and passing object as data
   var event = new CustomEvent('build', { 'detail': str });
   //dispatches the event which invokes the affected listeners
   this.dispatchEvent(event);
})

//Listening for 'build' event 
document.getElementById('parent').addEventListener('build', getData, true);

function getData(e){
  alert(e.detail);
}

Links shared which can help one to understand the concept. dispatchEvent & createCustomEvent .Hope that helps to answer your question! Added some comments & links which will help those who aren't aware of the functions & behavior used.

4 Comments

You should not try and explain a simple jQuery problem with lengthier raw Javascript.
Well!..thank you for your advice, but I seriously don't think that given code is lengthier and someone who understands jQuery will find anything questionable.
Your code is twice the size and complexity, so not sure how you defend "but I seriously don't think that given code is lengthier" :)
For those that cannot follow this code easily (as it is not that clear without explanation), it is generating a custom event inside a click handler. That custom event passes the desired value as a detail property of the jQuery event object you receive. Note: The same technique can be implemented with half as many lines of jQuery :)
0

If I understand the question maybe you can do something like this...

Variable = 5 is used within 2 functions...each function does something with it's value...
the last function uses the totals of the first 2 functions and again does something..
So the point is that u can access the 2 totals variables and use them in the third function...
As long as you set your function variable as global...so don't put VAR in front of it.
If you set var in front of it u are saying that your variable is private for that function...

Change the value of the original variable and all the values changes ....

     variable = 5;                    // this is a global variable
     source = $('div#een h2');        // put your source here

    function Init(){
        source.on('click', function(){
          Total1 = variable * 2;

          console.log(Total1);  // It outputs 10
        });
    };

    Init();

    function Init2(){
     source.on('click', function() {
          Total2 = variable * 5;   

          console.log(Total2); // It outputs 25
      });
     };

    Init2();

    function Init3(){
      source.on('click', function() {
          Total3 = Total1 * Total2; // here we use the 2 Totals...

          console.log(Total3); // outputs the Total of both totals... should be 250
      });
     };

    Init3();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.