Goal:
Have first input box background-color change to green (on target.html) after redirecting. It works if you go to the link explicitly (type it into the URL bar) in Google Chrome.
I’m using this version of Google Chrome:
13.0.782.112
It’s difficult to use jFiddle on this one, so I’ll just give you the code using the Content Delivery Network (CDN) jQuery file to make it easier for you.
See this question for more details:
Why doesn't initial page focus change input field to Green on Google Chrome?
Source page:
(name this page as source.html)
<html>
<head>
</head>
<body>
<a href="./target.html">click this hyperlink in Google Chrome and see if the background-color changes to green on the first input field on target.html</a>
</body>
</html>
Target page:
(name this page as target.html and place in same folder as source.html file)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function Change(obj, evt) {
if (evt.type == "focus") {
$(obj).css('border-color', '#000000');
$(obj).css('background-color', '#90EE90');
}
else if (evt.type == "blur") {
$(obj).css('border-color', '#FFFFFF');
$(obj).css('background-color', '#7AC5CD');
}
}
$(document).ready(function() {
$("#Txt1").focus();
});
</script>
<style type="text/css">
.InputField
{
color: black;
font-size: 12px;
font-weight: bold;
background-color: #7AC5CD;
}
</style>
</head>
<body>
<input id="Txt1" runat="server" class="InputField" onfocus="Change(this, event)" onblur="Change(this, event)" /><br />
<input id="Txt2" runat="server" class="InputField" onfocus="Change(this, event)" onblur="Change(this, event)" /><br />
<input id="Txt3" runat="server" class="InputField" onfocus="Change(this, event)" onblur="Change(this, event)" /><br />
</body>
</html>
Your best bet here is to bind those
onfocusandonblurevents dynamically instead of hardcoding them in the HTML. Something like this:This code should replace all of your current JavaScript, as well as the
onfocusandon blurattributes on those input boxes.With your current solution, it seems that there’s a bug in either jQuery or Chrome (or both) pertaining to triggering events that are bound in the HTML rather than through JavaScript. What happens, for whatever reason, is that the
DOMContentLoadedevent gets passed as the ‘evt’ variable instead of theonfocusevent.If you’re interested in exploring that bug further and perhaps even filing a bug report, you can see what happens in more detail by adding a
window.console.log(evt);statement to the first line of your Change function. Then open up the WebKit Web Inspector and look at the console, you’ll see the Event object there and you’ll notice that its type is ‘DOMContentLoaded’ even though it should actually be ‘focus’.