Hi there,

I am using a javascript code to refresh a page.

<code>
window.location.href="";
</code>

this code refereshes the whole page and focus goes at the top of the page but I want the focus of the page at the same place where I perform refresh.

Actually I am using AJAX to submit a form, a form opens through ajax request but I need to refresh the page to take the effect of the dynamic data, which is being saved,updated or deleted on the page.

So is there any way where focus of the page remains there when I refreshed the page, I hope you understand the question.

Please reply.

Take care.

Use the following method to refresh your page:

window.location.reload(); // Reloads' the page or.

self.location.reload(); // Reloads' the page and brings back focus.

just choose one...

If I understand correctly, then either:

  1. If you can, then use location.reload() as per Essential's suggestion, after receiving the response from your Ajax request, but be aware that location.reload() works as follows (from Danny Goodman: Dynamica HTML: O'Reilly):
    "reload([unconditional])
    "Performs a hard reload of the document associated with the location object. This kind of reload resets form elements to their default values (for a soft reload , use history.go(0)). By default the reload() method performs a conditional-GET action, which retrieves the file from the browser cache if the file is still in cache (and the cache is turned on). To force a reload from the server, force an unconditional-GET by adding the true Boolean parameter." As far as I can tell without experimenting ...... It appears that you would need to set the true parameter, so as not to reload from cache. You will need to discover by experiment whether location.reload(true) maintains focus (in all browsers!) as you want (it may behave like location.href=). You will also need to ensure that your form is rebuilt server-side with any user-entered values (as often performed when doing server-side form validation).
  2. Send a regular (non Ajax) form submit to refresh the page, including a dynamically determined parameter representing the id of the element currently with focus. Server-side, write some Javascript such that on page reload (client-side), it restores focus to the desired element. Again you will also need to ensure that your form is rebuilt server-side with any user-entered values. This could be made to work but is messy.
  3. Send Ajax request, but don't reload your page. Instead, dynamically rewrite values on your page using eg. xxx.value= or yyy.innerHTML= . This should automatically maintain focus, as nothing should have altered it. This is the typical (arguably "correct") modus operandi of Ajax and, I think, preferable to methods 1 or 2 if you are already committed to Ajax.

Airshow

Hi essential,

Thank you for your reply. I have tried both of them but page focus does not bring back, so what will be the solution??

Please reply.

Hi coolmind,

try doing this again:

window.location.href = location.href;

Ess, I think that will lose both focus and any user-entered form values.

Airshow

Hi,
It didnt work as welll, in this code page did not refresh and focus did not bring back either.

what is the best solution.

Hi,

Sorry if i have failed you with my last posted code! Im in a hurry when i posted up that code and not realizing that you need those data to be preserved.

Don't worry I'll try to figure out a way to solved this, just need a little more time &#8212; or maybe Airshow want to post his effective solution for this issue...

I'll post back when i'm done and good day to you...

Thanks Ess, I would like to post now but must attend an Annual General Meeting this evening (I am meeting Secretary) and then must write up the minutes. You may well get there before me.

Coolmind, maybe you could post your existing code and HTML to save having to start from scratch.

Airshow

So far this what i have... A demo that will preserved all scrolling activities in the window, and upon reload, it brings back the state were you last accessed it.
You can set all the values' you need inside the getXY() function.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>Test Page</title>
<style type="text/css">
/* <![CDATA[ */
html, body {
  border : none;
  font : normal normal normal 95%/1.6 Verdana, Arial, sans-serif;
  height : auto;
  margin : 0;
  padding : 0;
  min-width : 800px;
  text-align : center;
  width : auto; }

form, table {
  background-color : transparent !important;
  border : none;
  margin : 0 auto;
  padding : 0; }

table {
  border-collapse : collapse;
  min-height : 600px !important;
  width : auto; }

td {
  vertical-align : middle;}
input { display : block; vertical-align : middle; }

div#main {
  border : none;
  margin : 0 auto;
  width : 50%; } 
/* ]]> */
</style>

<script type="text/javascript">
// <![CDATA[
var  eDate;
var cookieActive;
var now = new Date();
cookieActive = Boolean( document.cookie );
eDate = new Date();
eDate.setTime( eDate.getTime() + (( 24 * 60 * 60 * 1000 ) * 31 ));

var cookies;
var getXY;

cookies = { 
      set : function( name, value, exp, path ) {
         if ( cookieActive ) {
            try {
            data = name  + "=" + (( value !== null ) ? escape( value ) : "" );
            data += (( exp !== null ) ? "; expires=" + exp.toGMTString() : "" );
            data += (( path !== null ) ? "; path=" + escape( path ) : "" );
            document.cookie = data;
            } catch( e ) {
      (( e.description ) ? alert( e.description ) : alert( e.message ));
            }
         } else { alert("Unable to create cookie!\nPlease make sure that your cookie is enabled in your browser...");
         }
      }, // Set Cookie Function
      del : function( name ) {
      expDate = now;
      expDate.setTime( expDate.getTime() - (( 24 * 60 * 60 * 1000 ) * 31 ));
         try {
         document.cookie = name + "=; expires=" + expDate.toGMTString() + "; path=/";
         } catch( e1 ) {
         (( e1.description ) ? alert( e1.description ) : alert( e1.message ));
         }
      }, // Delete Cookie Function
      get : function( name ) {
         if ( name !== null ) {
            try {
            lists = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
      return (unescape( RegExp.$2 )); 
            } 
            catch( e ) {   
            lists = document.cookie.indexOf( name + "="); 
               if ( lists !== -1 ) {
               lists = lists + name.length + 1;
               sem = document.cookie.indexOf(";", lists);
               sem = ( sem == -1 ) ? document.cookie.length : ""; 
               return ( unescape(document.cookie.substr( lists, sem )));
               }
            }
         }
      } // Get Cookie Function
   }; 


// You can edit everything inside the getXY() function. 
   getXY  = function() {

   var input = (( document.getElementById ) ? document.getElementById("txt") : document.all.txt ); // Form element (<input.../>)
   xPos = (( window.scrollX ) ? window.scrollX : window.pageXOffset ); // Get X coords. 
   yPos = (( window.scrollY ) ? window.scrollY : window.pageYOffset ); // Get Y coords.

   // Saving all the data using cookie. --->

   cookies["set"]("x", String( xPos ), eDate, "/"); // x position in pixel
   cookies["set"]("y", String( yPos ), eDate, "/"); // y position in pixel.
   cookies["set"]("text", input.value, eDate, "/"); // Text field value 
   };

// intiating getXY() function, with onmousemove event handler...

document.onmousemove = getXY;


// Restoring all data with onload event.
window.onload = function() {
  posX = Number(cookies["get"]("x")); // Get xPos.
  posY = Number(  cookies["get"]("y")); // Get yPos.
  textVal = (( cookies["get"]("text")) ? cookies["get"]("text") : "" ); // Get the text field value.

   var txtfield =  (( document.getElementById ) ? document.getElementById("txt") : document.all.txt );

   (( textVal !== "" ) ? txtfield.focus() : txtfield.blur() );
   txtfield.value = textVal 

// Bring's back focus to the window.
  if ( window.scrollTo ) {
  window.scrollTo( posX, posY ); 
   }
  else if ( window.scroll ) {
  window.scroll( posX, posY );
   } else { alert("Unable to load position!");
   }
}; 
// ]]>
</script>
</head>
<body>
<div id="main">
<table id="box" frame="void" rules="none" summary="Javascript DEMO">
<tr>
<td>
<form id="frm" action="#" onsubmit="return false;">
<div style="background-color : #f0f0f0; border : 2px solid #ddd; padding : 2em;"> 
<label for="txt">Enter some text <input type="text" id="txt" name="txt" size="20" value="" /></label> <button id="samp" name="samp" onclick="self.location.reload()">Refresh</button>
</div>
</form>
</td>
</tr>
</table>
</div>
</body>
</html>

Just let me know, if you get stuck with this.

Hi Essential,

Thank you for your reply, I am having difficulty understanding this Javascript code, I have difficulty about what this code is going to do.

please give me some more details about this code.

Thank you for your help.

Coolmind

Disregard this post...

Ok i'll provide you with some brief information about the code, when i get home. But for now, you try to run the whole document, so that you can see and understand how it works! If it still doesn't get what you need, then try posting back immediately so that i can re-apply another solution.
Or you can just post your code so that we can provide you, exact solution.

HI Essential,

Thank you for your reply. I will definitely run the whole document and will see how it works? First of all I want you to visit my live site so you can understand what I want.

The site address is
www.freelanceiq.net

use this information to log in.
login name = ahmad
password = kami123

when you get to the home page you will see profile listing. click on the edit link to go to the profile page.

In profile page, there are many forms like objective, skills,interests etc. In profile page I want you to add,edit and delete the dummy data to check for yourself.

Use firefox because there many browser compatibility issues in IE6.

Please reply.
Coolmind

Oh that's really bad! Exposing your username and password, publicly.

So have you tried the whole thing?

If my last posted solution doesn't fit in, then i'll try provide another shorter version of the script.

Since you are also using PHP, then you might also wanna' try posting back these issue over at PHP section.

Coolmind,

I've had a look at your page and believe that re-establishing focus is not really the issue so much as vertical scroll, in which case the solution is very very simple as steam-age HTML has the mechanism to handle this.

On the page wrap your section headings in a named anchor, eg.

..... <a name="objective"><span id="objective">Objective</span></a> ..... <a name="education"><span id="education">Education</span></a> .....
etc.

Now you have anchors to which the browser can be instructed to go by composing "refresh" urls with a hash (#) element at the right hand end. More specifically, you need to arrange for page refresh request URLs to be appended with the appropriate #name (ie, "#objective" or "#education" etc.)

There's a couple of ways you might consider. Both should work (after a little development effort):

Client-side: Build your "refresh" instruction in the format location.href = 'myprofile-25.fliq' + anchorName (where anchorName is a javascript variable containing "#objective", "#education", "#skills" etc.)

Server-side: In php, you should be able to use something like header("Location: $_SERVER['REQUEST_URI'] . $hashname); (where $hashname is a php variable containing "#objective", "#education", "#skills" etc.). I guess your script already contains suitable branching for each of these cases already, so it wouldn't be too hard to explore this method. I hasten to add that I haven't used php header() in a while so maybe someone with more experience would like to comment. Essential?

Hope this makes sense.

By the way, your page(s) need proper doctype, head and body. Browsers do pretty well without these but will do even better if they are given a some clues about what you really intended.

Airshow

I've been there and those fragment identifiers will only work if you know how to pick the spot.

Let's say if i point out, on this specified location in the page, and i want to bring back that portion of page --

now how would be able to instruct the browser to pick the right spot ( or anchors ) were i last accessed it?

It's easier said than done...

If you really think, it will work, then would you mind showing us some working script?

Seems that you know more things in this field, spending 10yrs compared in my 2 yrs experienced in the line of javascript.

I think i still need to learn from you.

P.S
I just want to thanked you, for adapting some of my patterns, inside your scripts.

Only 2 years Essential !! You amaze me. You are what I call a quick learner. After my first two years I was nowhere near where you are today. My excuse is that back in the '90s there was little reference material, and few good examples to follow. As for patterns, everybody did their own thing - patternless.

For a working example of using url hash to target a named anchor, you have one right here on Daniweb every time you use it! I'm looking at a url in my browser's address bar that ends with .....post873412.html#post873412 (that's Essential's post immediately above). The post873412.html part is interpreted by the server (it serves that page), while the #post873412 part is interpreted by the browser - it automatically scrolls down until the text inside the anchor is just in view - no script required. As far as I'm aware this is implemented and reliable in all the major browsers.

All you have to do is (a) wrap critical headings in <a name="myName">MyHeading</a> and (b) compose hyperlinks to include the #myName part.

Decidedly off topic from here .....

Now, I know I said no scripting involved and that's still true, but should you ever need to (I never have and you don't need to here) you can access this part of a url (read and write) with URL.hash (eg. window.location.hash ).

According to David Flanagan, Javascript The definitive Guide, 2nd Edn, 1997, O'Reilly (this is the book that Douglas Crockford holds up in one of his videos and says it's the only book on Javascript worth reading) the full list of url properties is (in alphabetical order):

  • URL.hash
  • URL.hash
  • URL.host
  • URL.hostname
  • URL.href
  • URL.pathname
  • URL.port
  • URL.protocol
  • URL.search

Thus, each part of a URL, should you ever need it, is available to Javascript without having to parse it out for yourself. All are read/write. The urls available to be used in this way are window.location (ie. self.location and other_accessible_windows.location) and the collection document.links. You can't create URLs other than by dynamically creating a hyperlink (typically with document.write() or document.createElement('a')). var foo = new URL(); generates an error.

I recall handling .pathname in javascript some years ago though I can't remember why now. Of the others I have only ever needed to read .search - this is the really useful one. Read all about it in my code snippet Javascript Query Parser. Comments/improvements welcome.

Airshow

Hi Airshow,

Wel, explained and as with Javascript is a very approchable language for beginners that quickly scales to be as a powerful tool as your skills allow....

at coolmind,
let's skip the hard coded page and use Airshow's suggetions.

Desired result can be achieved doing this implementation:

<label for="profile">Profile: <input type="text" id="profile" name="profile" value="<?php echo $_REQUEST['profile']; ?>" size="30" /></label><br />
<button id="btn" name="btn" onclick="self.location.href = './#profile'; /* Can be set dynamically */">SAVE</button>

This is just a bit of example on how you can implement and append those fragments in the URL.

With or without anchors' it will still get indexed by the browser as long as you provide valid ids that exist in the target document.

Hope i made it clear...

Aha, that's cool Ess! I hadn't thought of doing it that way.

Just some immediate thoughts:

  1. I think <button id="btn" name="btn" onclick="self.location.hash = 'profile';"> would do it.
  2. This would rely on the <form> action attribute being action="" , such that it submits with the default self.location . If the action was set explicitly then it would be used instead of self.location .
  3. If you wanted the <form> to submit with action="some_other_url" , then you could create a dummy <a href="xxx"> or use var foo = document.createElement('a'); , then set eg. form.action = foo.location , so you have an addressable url element, whose hash attribute foo.hash (and others) can be set independently of self.location.

This is all off-the-cuff - not tested and contains pseudo-code, therefore please treat with caution.

Airshow

It works!

The javascript below comprises a constructor and a single instance of it. Under different circumstances you might want to create two or more instances (for different urls).

You will see that formAction.setFragments(urlFrags) is written to accept an object of the format {urlProperty:'string'[, urlProperty:'string'] }. Hence you can use formAction.setFragments(urlFrags) to set url.hash and/or other url properties on one shot (see list of valid urlProprties in earlier post in this thread).

On clicking a link/button, two event handlers are involved -

  1. The form button's onclick handler establishes an appropriate url.hash name, then ...
  2. The form's onsubmit handler attaches an already established url as the form's action.

Note that I failed to get a <a>link version to work. It required use of form.submit(), which in IE6 (and other browsers?) does not fire the form's onsubmit event, presumably to avoid infinite recursion. However it may be possible to adapt the code to overcome this shorcoming.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Untitled</title>
<script language="JavaScript" type="text/javascript">
function FormAction(url){ //contructor
	var link = document.createElement('a');
	this.set = function(form) {
		if(form) {
			if(!form) { return true; }//allow submit even if no form specified
			form.setAttribute('action', link.href);
		}
	};
	this.setFragments = function(urlFrags) {
		if(urlFrags) {
			for(prop in urlFrags) { link[prop] = urlFrags[prop]; }
		}
	};
	this.setURL = function(url) {
		url = (!url) ? '' : url;
		link.href = url;
	};
	if(url) { this.setURL(url); }
};
var formAction = new FormAction(self.location);
</script>
</head>

<body>
<form id="f1" action="" method="post" onsubmit="formAction.set(this); return true;">
	<input type="submit" onclick="formAction.setFragments({hash:'education'}); return true;" value="Education" /><br><br>
	<input type="submit" onclick="formAction.setFragments({hash:'certificates'}); return true;" value="Certificates" /><br><br>
	<input type="submit" onclick="formAction.setFragments({hash:'employment'}); return true;"   value="Employment" /><br><br>
	<input type="submit" onclick="formAction.setFragments({hash:'bank_balance'}); return true;" value="Bank Balance" /><br><br>
</form>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<a name="education">Education</a>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<a name="certificates">Certificates</a>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<a name="employment">Employment</a>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<a name="bank_balance">Bank Balance</a>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
</html>

Should require only a little adaptation to fit in with existing code.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.