Why does this script not execute scrollTo(x,y) javascript? - javascript

Hello I am trying to create a refresh script to refresh a page on incomming messages,updated posts,ect. Why is x,y not executed useing ex: 1? I have seen a few different methods of reloading a page and keeping scroll position but they seem overkill. I think I would like to use ex: 2, is there any logical way to clear the server side variables using reload() or should I go another route for something like this?
function Refresh()
{
var x = window.pageXOffset;
var y = window.pageYOffset;
//ex 1:this works but doesnt keep scroll position
//window.location = window.location.href;
//ex 2: this works and retains x,y but doesnt refresh $_POST $_GET server side variables
window.location.reload();
window.location.scrollTo(x,y);
}
//for testing only
setInterval('Refresh()', 5000);

scrollTo is not executed because that line is never reached and also wrong. The moment you trigger a page load, script execution stops. Furthermore, window.location refers to the address-bar, basically, and scrollTo does not make sense here. Better would be window.scrollTo, but never mind:
A reload preserves scroll position (in most browsers) and $_GET variables, however browsers usually want user-confirmation to reload a POST-request. You probably do not want that behaviour.
The least "overkill" way to make the browser scroll to new content is using hash-tags, assuming you are in control of the updated content.
Just append something like #newcontent to your URL and set the id of your new content:
<div id="newcontent">Cool new post...
Browsers will auto-scroll to a fragment identifier.

Related

Differentiate automatic scroll after refresh from other kinds of scrolling

I have observed that after a refresh, by pressing F5 or even some location.reload();, the browser forces a scroll to the last position it was before the refresh.
The thing is, we track the user's progress across the page, and this "automatic" scroll fires all the checkpoints we have placed all the way to this last position before the refresh.
We are wondering whether is it possible to differ this "automatic" scroll from a scroll made by the user.
For instance, we have lots of:
$(window).scroll(function() {
var windowMax = $(window).scrollTop()+$(window).innerHeight()/2;
if (windowMax > .....)
});
Is there a way to differentiate this two sorts of scrolls?
Edit
Please, see that I don't want to prevent the automatic scroll, I want to differ it.
You can add a ready event listener and immediately check the .scrollTop() after it has been loaded.
var isScrolledAfterRefresh;
$(function() {
isScrolledAfterRefresh = $(window).scrollTop() > 0;
});
You do need to be sure that the rest of your code is executed after the ready event is fired.
This is something embedded in the users browsers. One way to counter it I suppose is to not have scrolling enabled on body or HTML, and have a custom scroll inside an element that is not on the top layer
You could also deffer recording of the scrolling until the page has fulling been rendered and the document completely loaded.
You could use the following to do stuff when the document is ready :
$(document).ready(function(){
// do stuff here
});

How to create the breadcrumb and the shifting view effect similar to Github

Clicking a breadcrumb link in github will trigger the directory view area to transition to the subdirectory . What is the best way to achieve this effect. I am using asp.net mvc , jquery, jquery ui, and a jquery layout plugin ( http://layout.jquery-dev.net/ ui layout )
Shoud I abandon the layout plugin ?
Well, you can start by using the unique url pattern. To make this sound a little familiar, let's take for example twitter:
#searching "stackoverflow"
https://twitter.com/#!/search/stackoverflow
the hash part is the one after (and including) "#". using window.location.hash gets it for us. then use string.replace() to remove #!/ and end up with:
search/stackoverflow
then if we store this value as a variable and do string.split('/'), which is split the value per /, we are returned with this:
array = ['search','stackoverflow'];
now it looks more like a breadcrumb which we can use to build. if you were in twitter, it would be more like:
site / search / stackoverflow
and for each breadcrumb link, just append further. if you have segmented urls, it's pretty easy to build the links:
site = mysite.com
site/search = mysite.com/search
site/search/stackoverflow = mysite.com/search/stackoverflow
for the sliding part, you need to pick up the "onhashchange" event which detects the changes to the value of the hash. The event always happens when you click a link that has href="#somevalue" - note the href having "#". you also notice that the page does not go anywhere (that's where AJAX magic comes to play later).
for modern browsers, you can detect hashchange using jQuery or plain JS:
$(window).on('hashchange',function(){
//do whatever you want when the hash changes
});
//or
window.onhashchange = function(){
//do whatever you want when the hash changes
}
for older browsers, you have to set a timer that checks the previous vs current value of the window.location.hash
(function timer(prevHash){
var currentHash = window.location.hash;
if(prevHash !== currentHash){
//do whatever you want when the hash changes
}
setTimeout(function(){
timer(currentHash);
},1000);
}();
the sliding effect can be achieved using jQuery .animate(). you can load the new page via AJAX (depending on the page you determined using the parsed hash), append the loaded page, slide the contents, and boom! you are done. It's pretty easy for everyone to make if they know the gears that make the clock turn.

Force page reload with html anchors (#) - HTML & JS

Say I'm on a page called /example#myanchor1 where myanchor is an anchor in the page.
I'd like to link to /example#myanchor2, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load.
The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use
where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.
Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.
Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so
I would still recommend just monitoring the hash though.
Simple like that
#hardcore
an example
Another way to do that is to set the url, and use window.location.reload() to force the reload.
<a href="/example#myanchor2"
onclick="setTimeout(location.reload.bind(location), 1)">
</a>
Basically, the setTimeout delays the reload. As there is no return false in the onclick, the href is performed. The url is then changed by the href and only after that is the page reloaded.
No need for jQuery, and it is trivial.
My favorite solution, inspired by another answer is:
myanchor2
href link will not be followed so you can use your own preference, for example: "" or "#".
Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both #Qwerty's and #Stilltorik's answers were causing the hash to disappear after reload for me.
What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.
This page has a hash monitor library and a jQuery plugin to go with it.
If you really want to reload the page, why not use a query string (?foo) instead of a hash?
Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.
Edit after comment
For example, you might have this code in your HTML:
example1
example2
example3
Then, you could add the following code to bind and respond to the links:
<script type="text/javascript">
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
</script>
Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.
Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.
Here's something like what I did (where "anc" isn't used for anything else):
And onload:
window.onload = function() {
var hash = document.location.hash.substring(1);
if (hash.length == 0) {
var anc = getURLParameter("anc");
if (anc != null) {
hash = document.location.hash = anc;
}
}
}
The getURLParameter function is from here
If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.
Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.
var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
Try this its help for me
<a onclick="location.href='link.html'">click me</a>
In your anchor tag instead of
click me
As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.
The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.
Here goes!
Move all the code that fires when a hash is detected into a separate independent function:
function openHash(hash) {
// hashy code goes here
return false; // optional: prevents triggering href for onclick calls
}
Then detect your hash for both scenarios like so:
// page load
$(function () {
if(typeof location.hash != typeof undefined) {
// here you can add additional code to trigger only on page load
openHash(location.hash);
}
});
// hash change
$(window).on('hashchange', function() {
// here you can add additional code to trigger only on hash change
openHash(location.hash);
});
And you can also call the code manually now like
Magic
Hope this helps anyone!
Try this by adding simple question mark:
Going to Anchor2 with Refresh

How to get scrollTop of page just after page onload event?

I know how to get the scrollTop of a page, I use this simple JS function (code copied around):
function GetScrolledTop()
{
//I never work in IE quirkmode, I always use DOCTYPE as 1st line, so I don't need to test for document.body.scrollTop
return self['pageYOffset'] || document.documentElement.scrollTop;
}
This works and my problem is the following: I tried to add it in the page onload event
<body onload="alert(GetScrolledTop());">
On page load I get ZERO (which make sense), but the problem is that I get ZERO even if I scroll the page and then reload it without touching the scrollbar.
It seems like the browser does:
loads page
calls my GetScrolledTop() (so obviously shows ZERO)
then scrolls the page to where it was before.
Do you know how to get the scolledTop after the step 3?
I mean how to get the scrolledTop AFTER the browser scrolled the page?
(maybe without using a timer)
Probably not without using a timer. But you might be able to use a timer with a 0ms delay, which would execute the function when the thread becomes idle, whilst still appearing to be instant:
<body onload="window.setTimeout(function () { alert(GetScrolledTop()); } , 0);">
EDIT - Thought it might also be worth mentioning that most browsers support the onscroll event, which should fire after the window scrolls.

How to prevent page's scroll position reset after DOM manipulation?

I've got two JS functions, one that is adding options to a select box
function addOption(selectId, text, value) {
var selectbox = document.getElementById(selectId);
var optNew = document.createElement('option');
optNew.text = text;
optNew.value = value;
try {
selectbox.add(optNew, null); //page position resets after this
}
catch(ex) {
selectbox.add(optNew);
}
}
and another that is doing a document.getElementById(formId).appendChild(newHiddenInput) in a similarly simple function.
They both work, elements are added as expected. However, upon calling either of them, the page resets its scroll position to the top of the page in both IE6 and FF. There is no postback, this is purely clientside manipulation. I've set breakpoints in Firebug, and it occurs immediately after the element.appendChild or select.add gets executed. I know I can use JS to manually set a scroll position, but I didn't think it was necessary when the page isn't being re-rendered.
I'm no expert with JS or the DOM, so I may very well be missing something, but I've looked here and ran through their examples with the Try it Here options and I can't replicate the problem, indicating the codebase I'm working with is the culprit.
Any ideas why the scroll position is being reset? jQuery is available to me as well, if it provides a better alternative.
If the functions are being called from a link you might have an internal anchor in your link:
http://www.website.com/page.html#
This is causing said behavior. The default behavior is that if an anchor does not exist, the page scroll position jumps to the top (scrollTop = 0).
If this happens on every function call regardless of the source, then this can be crossed off the list.
What is activating the event?
If it's an anchor then on the click event you need to "return false;" after the call to your jQuery/Ajax/jScript code.
If it's a button you may need to do the same.
I had this issue yesterday and this was the resolution.
So My link

Categories