Jquery/Javascript - Variable is taking another variables value

96 views Asked by At

Here is my Fiddle: http://jsfiddle.net/wr1k02ym/3/

Ignore the textboxes there, the textboxes are supposed to show up only when you double click the text but for some reason its showing in the fiddle (it works fine in my main program so I guess its a CSS issue.

Basically, I am displaying some text, if the text in a span like so:

<span class="output" title="lalalalalblas asdl sda lasdl asdb">lalalalalblas asdl...</span>

If the text is too long it only shows a bit of the text, and then on mouse over it shows the full text that is in the title.

In my Javascript I do the switching like so:

var tip;
var orig;
var switched = 0;
$('.output').hover(
    function () {
        tip = $(this).attr('title');
        orig = $(this).text();

        if (tip != orig) {
            $(this).fadeOut(function () {
                $(this).text(tip).fadeIn();
                switched = 1;
            });
        }
    },
    function () {
        if (switched == 1) {
            $(this).fadeOut(function () {
                $(this).text(orig).fadeIn();
                switched = 0;
                orig = "";
            });
        }
    });
});

As you can see my JS is pretty simple, but the problem arises (go to my fiddle to test) when you move your mouse from the below text onto the above text ... then for some reason this variable is taking the value of the other variable.

How do get it to work so that it does not take the other variables text?

1

There are 1 answers

4
Scott McDermid On BEST ANSWER

Your tip, orig, and switched vars are being shared between the handler functions, and thereby being shared between all elements. You could create vars for each element like this:

$('.output').each(function() {
    var tip;
    var orig;
    var switched = 0;

    $(this).hover(function () {
        tip = $(this).attr('title');
        orig = $(this).text();
        if (tip != orig) {
            $(this).fadeOut(function () {
                $(this).text(tip).fadeIn();
                switched = 1;
            });
        }
    }, function () {
        if (switched == 1) {
            $(this).fadeOut(function () {
                $(this).text(orig).fadeIn();
                switched = 0;
                orig = "";
            });
        }
    });
});

Now, there will be a tip, orig, and switched for each output element.

Fiddle: http://jsfiddle.net/wr1k02ym/4/