Reputation: 6255
I'm trying to set a default focus for all the pages of my site but without changing the focus on page reload.
I mean:
My current code is as follows:
$(document).ready(function() {
if($(':focus').length === 0) {
$(':input:not([type="hidden"]):first').focus();
}
});
The condition is true every time!
Upvotes: 1
Views: 1351
Reputation: 17757
$(document).ready({
window.onload=function(){
if(session.Storage.getItem("text3")){//if key= text3 is set,then change the focus to 3rd text box.
$('#your3rdTextID').focus();
}
$('#your3rdTextID').focus(function(){
session.Storaage.setItem("text3","selected")//here you set the key as text3 and value as selected for later use.
});
});
You can provide with your own custom conditions.This is just a small example.Hope it helped you.Good luck with your project.
LINK-->HTML5 Local storage vs. Session storage
LINK-->http://www.w3schools.com/html/html5_webstorage.asp
Upvotes: 2
Reputation: 9602
This will work (tested in latest Chrome, IE7 and IE10). Sets a cookie on focus remembering the last focused element, if not, it defaults to the first. It relies on jquery.cookie.js (usage explained in this SO answer). Here is the full HTML+JS source of a minimal working example. Consider changing the cookie name and the input selector (currently 'input'
):
<!doctype html>
<html>
<head>
<title>focus test</title>
<meta charset="utf-8" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var $input = $('input'), // get all the inputs
cookieName = 'lastInputFocusIndex', // for consistency
lastIndex = $.cookie(cookieName) || 0; // get the last known index, otherwise default to zero
$input.on('focus',function(){ // when any of the selected inputs are focused
if ( $(this).attr('type') !== 'submit' ) {
$.cookie(cookieName,$input.index(this)); // get their index in the $input list and store it
}
});
$input.eq(lastIndex).focus(); // when the page loads, auto focus on the last known index (or the default of 0)
});
</script>
</head>
<body>
<form method="get" action="">
<p><input type="text" name="first" /></p>
<p><input type="text" name="second" /></p>
<p><input type="text" name="third" /></p>
<p><input type="submit" value="Go" /></p>
</form>
</body>
</html>
Alternatively, you could write your own raw cookies instead of using the cookie helper jQuery plugin; I used it to simplify things.
Upvotes: 2