4

Fiddle: http://jsfiddle.net/vretc/

As you can see from the fiddle, I want to change color of span when hover on it, but somehow even I hover any in the first three element, the hover event just apply for the last span.

HTML

<p class="p">
    <span>Span 1</span>
</p>

<p class="p">
    <span>Span 2</span>
</p>

<p class="p">
    <span>Span 3</span>
</p>

<p class="p">
    <span>Span 4</span>
</p>

jQuery:

$('.p').each(function() {
    $span = $(this).children('span');
    $span.hover(
        function() {
            $span.css('color', 'red');
        },
        function() {
            $span.css('color', 'blue');
        }
    )
});

7 Answers7

6

Add var before $span:

var $span = $(this).children('span');

Currently, you're declaring a global variable, which will be overwritten at each iteration in the loop.

Updated Demo

Eli
  • 14,779
  • 5
  • 59
  • 77
5

You have only one global $span variable which after the loop will contain the last iterated element. Instead, make the variable local with a var declaration:

$('.p').each(function() {
    var $span = $(this).children('span');
    $span.hover(
        function() {
            $span.css('color', 'red');
        },
        function() {
            $span.css('color', 'blue');
        }
    )
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

There is no need for the .each()

You can try this:

$('.p').children('span').hover(
        function() {
            $(this).css('color', 'red');
        },
        function() {
            $(this).css('color', 'blue');
        });

check fiddle here

97ldave
  • 5,249
  • 4
  • 25
  • 39
1
$("p span").hover(function(){

  $("span ").css("color","red");
}).mouseout(function(){
$("p span ").css("color","black");
});
0

try this

  $('.p').each(function() {
   var $span = $(this).children('span');
   $span.hover(
    function() {
        $(this).css('color', 'red');
    },
    function() {
        $(this).css('color', 'blue');
    }
  )
});     

or without the loop (which is not required at all )

 $('.p').children('span').hover(
    function() {
        $(this).css('color', 'red');
    },
    function() {
        $(this).css('color', 'blue');
    }
  )
});     

fiddle here

bipen
  • 36,319
  • 9
  • 49
  • 62
0

Please check here http://jsfiddle.net/VREtC/2/

  $('.p').hover(
        function() {
            $(this).css('color', 'red');
        },
        function() {
            $(this).css('color', 'blue');
        }
    )
vinothini
  • 2,606
  • 4
  • 27
  • 42
0

If you want to make your code work, make $span a closure variable by using var

$('.p').each(function() {
    var $span = $(this).children('span');
    $span.hover(
        function() {
            $span.css('color', 'red');
        },
        function() {
            $span.css('color', 'blue');
        }
    )
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531