EnigmaMaster
EnigmaMaster

Reputation: 213

setting var as clicked button value and using var

Im setting the value of var x with the value of the clicked button. Then I want to use var x as the value in my jquery animation code.

var x = $('input').click(function() {
    $(this).val();
});

$("li").click(function() {
    $(this)
        .stop()
        .animate(
            {height:'150px'},
            {queue:false, duration:600, easing: x }
        );
});

$("li").mouseout(function() {  
    $(this)
        .stop()
        .animate(
            {height:'50px'},
            {queue:false, duration:600, easing: x });
});​

What am I doing wrong ? Demo : http://jsfiddle.net/EnigmaMaster/z9dXA/7/

Upvotes: 1

Views: 163

Answers (3)

nnnnnn
nnnnnn

Reputation: 150010

You're currently setting x equal to the jQuery object returned by $("input"). The .click() method sets up a click handler that will be called later (when the click happens), so it doesn't return the value at the time of the click - it returns the same jQuery object as $("input") so that you can chain multiple jQuery methods together. That's why your alert(y) was showing [object Object].

Try changing that first bit to this:

var x = "linear";  // give x a default value

$('input').click(function() {
    x = $(this).val();  // store the type of easing to be used
});

Then you don't actually need the y variable, you can just use x directly:

$("li").click(function() {
    $(this).stop().animate({ height: '150px' }, {
        queue: false,
        duration: 600,
        easing: x
    });
});

$("li").mouseout(function() {
    $(this).stop().animate({ height: '50px'}, {
        queue: false,
        duration: 600,
        easing: x
    });
});​

Updated demo: http://jsfiddle.net/z9dXA/9/

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

demo jsFiddle

var x = '';    // define your var (make it re-usable inside functions)

$('input').click(function() {
   x = $(this).val();   // set your var'x' value for use.
});

$("li").click(function() {   
    $(this).stop().animate({height:150},{queue:false, duration:600, easing: x });
});
    
$("li").mouseout(function(){  
    $(this).stop().animate({height:50},{queue:false, duration:600, easing: x });
});

Upvotes: 4

Koen Peters
Koen Peters

Reputation: 12916

The click is asynchronous. Do it like this:

var x;
$('input').click(function() {
    x = $(this).val();
});

See fiddle: http://jsfiddle.net/z9dXA/8/

This will only work if the input is clicked before the li's are by the way, otherwise the x will have no value. Maybe provide a default value such as this:

var x = 'swing';
$('input').click(function() {
    x = $(this).val();
});

Upvotes: 2

Related Questions