April 20, 2012

Can I store some variable into the hover function?

Question by markzzz

Seems that I can’t store the linguettaCorrente variable into the hover handler :

$('.navigatore_blocco').hover(
    var linguettaCorrente=$(this).find('linguetta');

    function() {
        linguettaCorrente.animate( { height: 33 }, 600);
    },

    function() {
        linguettaCorrente.animate( { height: 23 }, 600);
    }
);

why? And how can I store it?

Answer by Vega

Declare the same var outside the hover and define it inside.

var linguettaCorrente = null;
$('.navigatore_blocco').hover(
    function() {
        linguettaCorrente = $(this).find('linguetta');
        linguettaCorrente.animate( { height: 33 }, 600);
    },
    function() {
        linguettaCorrente.animate( { height: 23 }, 600);
    }
);

.hover function takes 2 argument and those 2 are functions. It cannot be anything else.

Answer by Starx

Why dont you use .data() to store the needed data?

$('.navigatore_blocco').hover(
    var linguettaCorrente=$(this).find('linguetta');
    $(this).data('linguetaaCorrente', linguettaCorrente);
    ....
);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!