ak85
ak85

Reputation: 4264

Undefined variable when hovering

I have two lists, When I hover on Tom in one-list I want the description about him to go red so I have added a class of hover as shown below. The problem I am having is I can't remove the hover state as I am getting undefined when I am leaving the hover state. I have commented out the few things I have tried so far. Is there a way to either know the value of id or remove any class called hover on the page when I leave the hover?

    <ul id="one-list">
        <li id="u11">Tom</li>
        <li id="u22">Jerry</li>
    </ul>

    <ul id="another-list">
        <li id="a11">Tom is 22 years old</li>
        <li id="a22">Jerry is 18 years old</li>
    </ul>

    $("#one-list li").hover(

    function () {
        var id = jQuery(this).attr('id') || '';
        id = id.replace(/u/, '');
        $('#another-list #a' + id ).addClass("hover");
    }, function () {
        //$('body').removeClass("hover");
        //$('#another-list #a' + id ).removeClass("hover");
    }
    );

    .hover {
        color:red;
    }

Upvotes: 0

Views: 389

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149020

You're getting that error because id is only defined within the first function. You'd need to get the id again in the second function, for example:

$("#one-list li").hover(
    function () {
        var id = jQuery(this).attr('id') || '';
        id = id.replace(/u/, '');
        $('#another-list #a' + id ).addClass("hover");
    }, function () {
        var id = jQuery(this).attr('id') || '';
        id = id.replace(/u/, '');
        $('#another-list #a' + id ).removeClass("hover");
    }
);

Or more simply

$("#one-list li").hover(
    function () {
        var id = this.id.replace('u', '');
        $('#another-list #a' + id ).addClass("hover");
    }, function () {
        var id = this.id.replace('u', '');
        $('#another-list #a' + id ).removeClass("hover");
    }
);

Or even better:

 $("#one-list li").hover(
    function () {
        var id = this.id.replace('u', '');
        $('#another-list #a' + id ).toggleClass("hover");
    }
 );

Upvotes: 3

E. S.
E. S.

Reputation: 2919

try this.. put a 'temporary' variable with the another list element.. i don't understand why you remove 'u' from id.. but...

http://jsfiddle.net/ND3p8/3/

(function($){

    var $listItem = $("#onelist li");
    var $anotherListItem = null;

    $listItem.hover(function(){ //handlerIn

        var $item = $(this);
        var id    = $item.attr('id');


        id = id.replace(/u/,''); //replace letter 'u'...why?

        $anotherListItem = $("#a"+id);

        if( $anotherListItem ){
            $anotherListItem.addClass('hover');
        }

    },function(){ //handlerOut

        if( $anotherListItem ){
            $anotherListItem.removeClass('hover');
        }

        $anotherListItem = null;

    });


})(jQuery);

Upvotes: 0

Related Questions