Make Page Jump to Anchor on Reload - javascript

Greetings I'm working on a gallery script and would like to have it so when the page is loaded it is automatically positioned to the top of an anchor I have set. I've tried this code:
<script>location.href = "#trendnav";</script>
<a name="trendnav"></a>
And it doesn't seem to do anything. The more instantaneous this seems to the user, the better.

Try
window.location.hash = "#VALUE";
Fiddle Demo 1
Fiddle Demo 2
or
window.scrollTo

Or, using your original approach:
$('span#godown').click(function(){location='#anchor';});
See here http://jsfiddle.net/dxNKG/1/
. I assigned a clickable span with the task of being the button that triggers it.
Actually, your original syntax location.href='#anchor' is correct, but you should fire it only after the DOM has loaded completely. So, either put the <script> section at the end of your page or do something like
window.onload=function(){window.location.href='#anchor';};
see here http://jsfiddle.net/bUaTT/ (without jQuery)
or, since you are using jQuery:
$(function(){window.location.href='#anchor';})

Related

window.reload() - reload to top of page of anchor

Consider the following inline code below:
<h1 id="top">Top Of Page</h1>
...
<a class='reload' onClick='window.location.reload();'>Reload</a>
How would one implement this in a fashion where when the window reloads, it goes to the top of the page of hits the anchor? I tried just doing:
reload to top of page
$(window).on('load', function(){
$('html, body').scrollTop(0);
});
and:
Reload browser does not reset page to top
$(document).ready(function(){
$(this).scrollTop(0);
});
Directly in the related template but it wouldn't load to top? Besides jQuery not being included Why would that be?
Is there a way to do this inline to keep consistent? so something like (which I tried):
<a class='reload' onClick='window.location.reload().scrollTop(0);'>Reload</a>
Which doesn't go to the top of the page, either.
I then thought to do the href of the id I can anchor to:
anchor jumping by using javascript (slightly tweaked to my situation)
<script type="text/javascript">
function goToTop(){
var url = location.href;
location.href = url + "#top";
}
</script>
<a class='reload' onClick='goToTop()'>Reload</a>
In this approach, it just adds "#top" to the URL and nothing else.
I was under the impression what if you change location.href it redirects to the new URL. It says here that "The href property sets or returns the entire URL of the current page." Why won't it set it in the above function?
This seems pretty simple so I'm not understanding what I'm missing?
You just need to add window.location.reload(true) after the line where you set [window.]location.href to your anchor.
Related
Posting answer by #epascarello embedded in comments, above, as it worked for me and is the simplest answer I've seen.
If you don't need/want any animated reload actions, simply use two different events - first to move the current page/scroll location to the top [window.scrollTo(0,0);] and then reload the page, either from the cache [window.location.reload();] or from the server if you've updated any of the needed data [window.location.reload(true);]. So,
// Moving page to top on forced reload in javascript
window.scrollTo(0,0);
window.location.reload(); //or window.location.reload(true) to use new/updated data from the server
Hope this helps others. Thanks, again, #epascarello!

Page blinking while clicking on it | jQuery .load()

Two questions.
When i'm loading to div file via jQuery .load()
$('.class').click(function(){
$(this).load("file.php");
});
file.php is loading properly, but whenever i click on it (doesn't matter where, just in file.php zone), page is blinking. Something like page refresh on click. Is there a way to prevent that?
Also the position of this page is always relative to div. Why doesn't position: absolute; on body in seperate css file for file.php work for file.php? I want to reset the position of file.php to be on top of website (not z-index). Thanks.
Your code
$('.class').click(function(){
$(this).load("file.php");
});
says any time you click in that div, (re)load the contents.
You may want to use jQuery's one method instead
$('.class').one("click", function(){
$(this).load("file.php");
});
which will only execute the first time you click inside the div.
As to position, we'd need to see code. Possibly one of your parent elements has position: relative?
Easy way.
$('.class').one("click", function(){
$(this).load("file.php");
});
Also is better to use .ajax() for this to have more options and better control.
.load() sometimes can first destroy content and then load new one. If you load bunch amount of data, that can made blink effect.

Trying to load another html page into a div using jQuery. I looked at other posts but mine still isn't working

Please have a look. EDIT: here is a link to a fiddle for the entire code: http://jsfiddle.net/e77aqubx/
This is a section of the jQuery (everything above it seems to be working fine). I am trying to get portfolio.html to show up in the #portfolio div (which is not visible until you click the link for it). The portfolio.html is in the same folder in the directory so I don't think I have to worry about the link.
$("#portfolio_link").click(function(){
$(".header").hide();
$("#about").hide();
$("#portfolio").show();
$("#portfolio").load("portfolio.html");
});
I have a div set up for it in the html as
<div id="portfolio">ooh blah dee</div>
In the jQuery I also tried:
$("#portfolio").show(function(){
$("#portfolio").load("portfolio.html");
});
Have you considered using IFrames? If I understand your issue correctly you can simply change the display of the element on action using something like .toggle()
example: JSFiddle
Edit:
As far as the current code, i would really need to see some more info as your code appears, at a simple form anyway, correct. Can you provide your file structure, or the results from the networking tab in dev tools when you run the event? Or even give this a shot on your .load():
$( "#portfolio" ).load( "portfolio.html", function() {
alert( "Load was performed." );
});
However it's important to remember that .load() is an ajax call so everytime you run your display method you're rendering a view via ajax instead of that one time iframe.
Hmm, the problem might be that the #portfolio_link element is created in the DOM after you attempt to attach the event listener. This could be solved by attaching the event listener to the 'body' tag and filtering down to any click events on children matching the '#portfolio_link' DOM selector.
Try this:
$('body').on('click', '#portfolio_link', function(){
$('.header').hide();
$('#about').hide();
$('#portfolio').show();
$('#portfolio').load('portfolio.html');
});
Jquery works in chain.
Also try first to load and then hide.
Can you use Firebug or Chrome devoper tools to see
what is happening with DOM?

Page reload doesn't reset jQuery / CSS styles

I'm designing an HTML page which has one button. The user clicks the button and a simple jQuery script animates that div away, revealing lower page content. You can see it here.
I've noticed that it looks/works fine the first time, but if I refresh the page with the browser button, it doesn't fully reset. The initial container is only half on the page. If I enter the URL again and load the page, it resets as expected.
NOTE: This only happens if you scroll down a bit after clicking the initial button... which seems weird.
I had no idea that there was any difference between these two operations, but there clearly is. What is the difference and how can I fix this problem from happening?
Here's my jQuery code, in case it's relevant:
$(document).ready(function(){
var faqs = $("#FAQ");
$("#learnmore").click(
function(){
$("#home").animate({top:'-=1066px'},600);
$("#more").animate({top:'-=1066px'}, 600, function() {$("#background").hide();} );
$("body").css('overflow-y', 'scroll');
//$("#home").slideUp();
console.log("jquery loaded");
}
);
});
It happens because it is cached by the browser.
If you styles are regularly modiefied, then as easy fix is to attach a unique id on the end of the reference, like
<link href="style.css?time=168768234928" ..../>
What it does, it makes the browser think it is a new request everytime it loads.
It happens because browser trying to scroll to the same position, what was before page reload. To check it, try press button and don't scroll to bottom of page and then reload page.
Okey, the reason is clear.
Now we need solution. Try this:
#more {display:none}
in your css. And then use
$("#more").show().animate(...
in your $("#learnmore").click() function. I hope this will solve the problem.

HTML anchor link with no scroll or jump

I have various links which all have unique id's that are "pseudo-anchors." I want them to affect the url hash value and the click magic is all handled by some mootools code. However, when I click on the links they scroll to themselves (or to the top in one case). I don't want to scroll anywhere, but also need my javascript to execute and to have the hash value in the url update.
Simulated sample code:
button 1
button 2
Home
So if you were to click on the "button 1" link, the url could be http://example.com/foo.php#button1
Does anyone have any ideas for this? Simply having some javascript return void kills the scrolling but also kills my javascript (though I could probably work around that with an onclick) but more importantly, prevents the hash value in the url to change.
The whole point of an anchor link is to scroll a page to a particular point. So if you don't want that to happen, you need to attach an onclick handler and return false. Even just adding it as an attribute should work:
button 1
A side of effect of the above is that the URL itself won't change, since returning false will cancel the event. So since you want the URL to actually change, you can set the window.location.hash variable to the value that you want (that is the only property of the URL that you can change without the browser forcing a reload). You can probably attach an event handler and call something like window.location.hash = this.id though I'm not sure how mootools handles events.
(Also you need all of the IDs to be unique)
You can use the code below to avoid scrolling:
linktxt
I'm probably missing something, but why not just give them different IDs?
button 1
button 2
Home
Or whatever convention you'd prefer.
Also, preventDefault
$(your-selector).click(function (event) {
event.preventDefault();
//rest of your code here
}
I found the solution. Here I save an old location from calling href
and restore it after scrolling
<script language="JavaScript" type="text/javascript">
<!--
function keepLocation(oldOffset) {
if (window.pageYOffset!= null){
st=oldOffset;
}
if (document.body.scrollWidth!= null){
st=oldOffset;
}
setTimeout('window.scrollTo(0,st)',10);
}
//-->
</script>
and in body of page
<a href="#tab1" onclick="keepLocation(window.pageYOffset);" >Item</a>
Thanks to sitepoint
An easier way would probably be to add it as a GET. That is, http://example.com/foo.php?q=#button1 instead of http://example.com/foo.php#button1
This won't have any effect on how the page is displayed (unless you want it to), and most scripting languages already have tools in place to easily (and safely) read the data.
Well here we are 7 years after this answer was published and I found a different way to make it work: just point the window.location.hash to a non-existent anchor! It doesn't work for <a>s but works perfectly in <div>s.
<div onclick="window.location.hash = '#NonExistentAnchor';">button 1</div>
Worked fine in Chrome 56, Firefox 52 and Edge (IE?) 38. Another good point is that this doesn't produce any console errors or warnings.
Hope it helps somebody besides me.
There is a solution without any JavaScript at all:
I will not jump to the top
Use
button 1
where
function setHash(hash) {
event.preventDefault();
history.pushState(null, null, "#"+hash);
}
event.preventDefault() stops browser from what it normally would do on clicking, and history.pushState adds to the sessions history stack.
For further discussion, see here and here

Categories

Resources