I have the following script which randomly assigns different colours (from an array) to letters in a DIV and changes these colours on hover. The script is supposed to change the colours back when the mouse leaves the DIV (i.e. when no hover). It is doing so in Firefox, but not in other browsers (Safari, Chrome and IE). Also the click function isn’t working properly in these browsers either (again it is in Firefox).
You can see the script in action here.
I wonder if someone can help troubleshoot this?
Thanks,
Nick
$(document).ready(function() {
var test = $("#example p").text().split('');
var normal = generateColors(test);
var hover = generateColors(test);
$("#example p").html(normal);
$("#example").hover(
function(event) { $("#example p").html(hover) },
function(event) { $("#example p").html(normal) });
$("#example").click(function() {
location.href = "http://www.google.co.uk";
});
});
function generateColors(characters) {
var result = "";
var i = 0;
for(i=0; i < characters.length; i++) {
result += "<span style='color:"+getColor()+"'>"+characters[i]+"</span>";
}
return result;
}
function getColor() {
var colList = ['#7EA404', '#14AFB0','#B05718', '#B0A914', '#B01617','#902BB0', '#B003A2', '#4A429C','#33821E', '#226795', '#D0B600','#886833'];
var i = Math.floor((Math.random()*colList.length));
return colList[i];
}
The problem seems to be that it’s not always picking up the mouseleave event when you’re hovering over text. The simplest solution is to add padding to the div so that there is space between the text and the edge of the container. Fiddle