Why last element always fired on hover?

error-handling, javascript, jquery, jquery-selectors, onhover

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

Problem

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

Original source