Focus Detection in C #

I have an update panel that causes a postback to parts of the page, and after the postback, a control that had focus (which is not in the update panel) loses focus. How can I determine which control was focused and store this value so that I can reorient on it when the page reloads. Thanks.

+4
source share
3 answers

First I snap the focus to all inputs and keep the last focused control identifier. Then, after UpdatePanel completes the download, I set the focus to the last

// keep here the last focused id var LastFocusedID = null; function watchTheFocus() { // on every input that get the focus, I grab the id and save it to global var $(":input").focus(function () { LastFocusedID = this.id; }); } var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_initializeRequest(InitializeRequest); prm.add_endRequest(EndRequest); function InitializeRequest(sender, args) { } // after the updatePanel ends I re-bind the focus, and set the focus // to the last one control function EndRequest(sender, args) { if(LastFocusedID != null) $('#' + LastFocusedID).focus(); watchTheFocus(); } jQuery(document).ready(function() { watchTheFocus(); }); 

I only think that I use jQuery to create it, but I present my idea here, you can do it with less code with jQuery.

+1
source

You can get which element is focused on javascript using the activeElement property and hasFocus for the HTMLDocument object.

This may not be supported by everyone, as it is HTML5.

0
source

You can solve this problem

 var last_focused = null; $(function () { //store last focused element. $("input").live("focus", function(){ last_focused = $(this); }); }); //in Script manager var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_pageLoaded(pageLoaded); function pageLoaded(sender, args) { if(last_focused != null) { last_focused.focus(); } } 
0
source

Source: https://habr.com/ru/post/1392919/


All Articles