Question

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');
        }
    )
});
Was it helpful?

Solution

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

OTHER TIPS

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');
        }
    )
});

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

$("p span").hover(function(){

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

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

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top