jQuery: how to scroll to certain anchor/div on page load? - javascript

Lately im trying to use jquery more often and right now im having some problem i'd like to solve with jquery hope u could help me.
I have some web page that includes some anchor tag (lets say the anchor is located in the middle of the page) and on the event onload i want the page to start on that certain anchor tag location meaning the page will be "scrolled" automaticaly to a certain location.
That was my previous solution (which is quite ugly since it adds #i to my url)
window.onload = window.location.hash = 'i';
Anyway could u tell me how can i do it with jquery?
notice: i don't want the user to feel any slide or effect while getting to this location

Use the following simple example
function scrollToElement(ele) {
$(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left);
}
where ele is your element (jQuery) .. for example : scrollToElement($('#myid'));

There's no need to use jQuery because this is native JavaScript functionality
element.scrollIntoView()

I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.
Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.
$(document).ready(function(){
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var hash = location.hash.replace('#','');
if(hash != ''){
// Clear the hash in the URL
// location.hash = ''; // delete front "//" if you want to change the address bar
$('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);
}
});
});
See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.

i achieve it like this..
if(location.pathname == '/registration')
{
$('html, body').animate({ scrollTop: $('#registration').offset().top - 40}, 1000);
}

Have a look at this
Appending the #value into the address is default behaviour that browsers such as IE use to identify named anchor positions on the page, seeing this comes from Netscape.
You can intercept it and remove it, read this article.

/* START --- scroll till anchor */
(function($) {
$.fn.goTo = function() {
var top_menu_height=$('#div_menu_header').height() + 5 ;
//alert ( 'top_menu_height is:' + top_menu_height );
$('html, body').animate({
scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px'
}, 500);
return this; // for chaining...
}
})(jQuery);
$(document).ready(function(){
var url = document.URL, idx = url.indexOf("#") ;
var hash = idx != -1 ? url.substring(idx+1) : "";
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var anchor_to_scroll_to = location.hash.replace('#','');
if ( anchor_to_scroll_to != '' ) {
anchor_to_scroll_to = '#' + anchor_to_scroll_to ;
$(anchor_to_scroll_to).goTo();
}
});
});
/* STOP --- scroll till anchror */

just use scrollTo plugin
$("document").ready(function(){
$(window).scrollTo("#div")
})

Just append #[id of the div you want to scroll to] to your page url. For example, if I wanted to scroll to the copyright section of this stackoverflow question, the URL would change from
http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load
to
http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load#copyright
notice the #copyright at the end of the URL.

Related

When hash is added on url, scroll stops working on mozilla firefox [duplicate]

I have a sliding panel set up on my website.
When it finished animating, I set the hash like so
function() {
window.location.hash = id;
}
(this is a callback, and the id is assigned earlier).
This works good, to allow the user to bookmark the panel, and also for the non JavaScript version to work.
However, when I update the hash, the browser jumps to the location. I guess this is expected behaviour.
My question is: how can I prevent this? I.e. how can I change the window's hash, but not have the browser scroll to the element if the hash exists? Some sort of event.preventDefault() sort of thing?
I'm using jQuery 1.4 and the scrollTo plugin.
Many thanks!
Update
Here is the code that changes the panel.
$('#something a').click(function(event) {
event.preventDefault();
var link = $(this);
var id = link[0].hash;
$('#slider').scrollTo(id, 800, {
onAfter: function() {
link.parents('li').siblings().removeClass('active');
link.parent().addClass('active');
window.location.hash = id;
}
});
});
There is a workaround by using the history API on modern browsers with fallback on old ones:
if(history.pushState) {
history.pushState(null, null, '#myhash');
}
else {
location.hash = '#myhash';
}
Credit goes to Lea Verou
The problem is you are setting the window.location.hash to an element's ID attribute. It is the expected behavior for the browser to jump to that element, regardless of whether you "preventDefault()" or not.
One way to get around this is to prefix the hash with an arbitrary value like so:
window.location.hash = 'panel-' + id.replace('#', '');
Then, all you need to do is to check for the prefixed hash on page load. As an added bonus, you can even smooth scroll to it since you are now in control of the hash value...
$(function(){
var h = window.location.hash.replace('panel-', '');
if (h) {
$('#slider').scrollTo(h, 800);
}
});
If you need this to work at all times (and not just on the initial page load), you can use a function to monitor changes to the hash value and jump to the correct element on-the-fly:
var foundHash;
setInterval(function() {
var h = window.location.hash.replace('panel-', '');
if (h && h !== foundHash) {
$('#slider').scrollTo(h, 800);
foundHash = h;
}
}, 100);
Cheap and nasty solution.. Use the ugly #! style.
To set it:
window.location.hash = '#!' + id;
To read it:
id = window.location.hash.replace(/^#!/, '');
Since it doesn't match and anchor or id in the page, it won't jump.
Why dont you get the current scroll position, put it in a variable then assign the hash and put the page scroll back to where it was:
var yScroll=document.body.scrollTop;
window.location.hash = id;
document.body.scrollTop=yScroll;
this should work
I used a combination of Attila Fulop (Lea Verou) solution for modern browsers and Gavin Brock solution for old browsers as follows:
if (history.pushState) {
// IE10, Firefox, Chrome, etc.
window.history.pushState(null, null, '#' + id);
} else {
// IE9, IE8, etc
window.location.hash = '#!' + id;
}
As observed by Gavin Brock, to capture the id back you will have to treat the string (which in this case can have or not the "!") as follows:
id = window.location.hash.replace(/^#!?/, '');
Before that, I tried a solution similar to the one proposed by user706270, but it did not work well with Internet Explorer: as its Javascript engine is not very fast, you can notice the scroll increase and decrease, which produces a nasty visual effect.
This solution worked for me.
The problem with setting location.hash is that the page will jump to that id if it's found on the page.
The problem with window.history.pushState is that it adds an entry to the history for each tab the user clicks. Then when the user clicks the back button, they go to the previous tab. (this may or may not be what you want. it was not what I wanted).
For me, replaceState was the better option in that it only replaces the current history, so when the user clicks the back button, they go to the previous page.
$('#tab-selector').tabs({
activate: function(e, ui) {
window.history.replaceState(null, null, ui.newPanel.selector);
}
});
Check out the History API docs on MDN.
This solution worked for me
// store the currently selected tab in the hash value
if(history.pushState) {
window.history.pushState(null, null, '#' + id);
}
else {
window.location.hash = id;
}
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');
And my full js code is
$('#myTab a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
var id = $(e.target).attr("href").substr(1);
if(history.pushState) {
window.history.pushState(null, null, '#' + id);
}
else {
window.location.hash = id;
}
// window.location.hash = '#!' + id;
});
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
// console.log(hash);
$('#myTab a[href="' + hash + '"]').tab('show');
I'm not sure if you can alter the original element but how about switch from using the id attr to something else like data-id? Then just read the value of data-id for your hash value and it won't jump.
When using laravel framework, I had some issues with using a route->back() function since it erased my hash. In order to keep my hash, I created a simple function:
$(function() {
if (localStorage.getItem("hash") ){
location.hash = localStorage.getItem("hash");
}
});
and I set it in my other JS function like this:
localStorage.setItem("hash", myvalue);
You can name your local storage values any way you like; mine named hash.
Therefore, if the hash is set on PAGE1 and then you navigate to PAGE2; the hash will be recreated on PAGE1 when you click Back on PAGE2.

Page scroll to right page from menu anchor but not from direct link

I'am using this free script
http://codyhouse.co/gem/css-faq-template/
http://codyhouse.co/demo/faq-template/index.html#payments
The demo has the same problem as my website, although it's even worse on my website.
If you use the menu, everything works fine. You have some space above the header.
But if you visit the direct link http://codyhouse.co/demo/faq-template/index.html#payments not from the menu
it looks like this
As you can see, there is no space above the header "payments".
It is even worse on my page. It starts at "Can I have.." and the header is hidden. Can not find where I can adjust this when I visit the page direct from the link without it effects how it looks when I visit the section from the menu.
When user clicks on a section
//select a faq section
faqsCategories.on('click', function(event){
event.preventDefault();
var selectedHref = $(this).attr('href'),
target= $(selectedHref);
if( $(window).width() < MqM) {
faqsContainer.scrollTop(0).addClass('slide-in').children('ul').removeClass('selected').end().children(selectedHref).addClass('selected');
closeFaqsContainer.addClass('move-left');
$('body').addClass('overlay');
} else {
$('body,html').animate({ 'scrollTop': target.offset().top - 69}, 200);
}
});
Javascript code: http://codyhouse.co/demo/faq-template/js/main.js
Style: http://codyhouse.co/demo/faq-template/css/style.css
Just a quick hack, use
if(window.location.hash) {
// if url contain '#'
// scroll down a few pixle
}
EDIT:
it's hard to demenstrated this in jsfiddle, since it won't let me play with the # hash.
var url = 'http://example.com/test.html#hash';
//you can get by using window.location.href
var hash = url.split('#')[1];
// this get the 1st hash variable
if(hash) {
// if hash exist
$('html, body').animate({
scrollTop: "5000px"
}, 0);
// scroll down a little bit
}
It's seems there's a couple of problems here. For me it looks like everything happens when a scrolling event fire.
Try this:
$(document).ready(function(){
$(window).scroll();
})

How can i create a link outside my webpage with the goal to open my webpage in an anchor and then load a iframe?

I tried with this code but, didn´t worked.
<a href="http://altodesign.pt/#portfolio" onClick="loadintoIframe('myframe,'portfolio/mmteam.html');">
you can try something like this
a href="javavcipt:document.getElementById('myframe').src = 'portfolio/mmteam.html';"
I would never use javascript ...
I have had a look into your webpage (plenty to learn, like add scripts to the end of the page, create a global javascript object to hold all website actions, etc ... but that's not the question)
I could see that, even thought you jump to #CONTACTOS you are not making the use of the hash at all... and you should!
using the hash would let you do things like:
http://altodesign.pt/#portfolio-cooptaxis
and that would jump to portfolio anchor and load the cooptaxis.html into the iframe and you stoped using javascript:loadintoIframe('myframe', 'portfolio/mmteam.html') at all, as that will cause Google Analytics and Crawlers not to follow up your links for example ...
your method could be something simple like
$(function() {
// let's see if we have an hash on the page
var hash = document.location.hash;
if(hash.length > 0) {
if(hash.instr('-') >= 0) {
// supposing will have only one char '-'
var img = hash.split('-')[1];
// let's remove the frame info from the hash
hash = hash.split('-')[0];
// there's a call to load into the iframe, let's load it
$("#myframe").attr("src", "portfolio/" + img + ".html")
}
// let's fly
jumpTo(hash);
}
// let's disable the anchor links by default and use the hash
$("a[href^=#]").click(function() {
// for all links that start with the hash, let's...
document.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function() {
// everytime the hash changes let's fly
jumpTo(document.location.hash);
});
});
function jumpTo(anchor) {
var a = $("a[name='" + anchor.replace('#','') + "']"),
pos = 0;
if(a.length > 0) {
// we have found the anchor, let's grab it's top position
pos = a.position().top;
}
// if we got here and pos === 0, we did not found the anchor
// for the given hash... maybe the user is playing around ...
// and we shall fly
$('body,html').animate({
scrollTop: pos
}, 800);
}
justthis will allow you to avoid using javascript to jump your links, as all they now have to have is simple: Portfolio
Let we say that you have page1.html in-which a link to page2.html you want it to be opened in an iframe in page1.html
in page1.html
link
<iframe name="iframe-name"></iframe>
Then you are able to add any anchor you want. It is just a matter of naming your iframe and then targeting it in the link!

Using jQuery-Smooth-Scroll from one page to another?

I am currently using jQuery-Smooth-Scroll to smoothly scroll up and down to various anchor positions on one of my pages (Page 1). However, what I would also like to be able to do is, from another page (Page 2), link to Page1 (appending #bookmark to the url) and have jQuery-Smooth-Scroll pick up on the fact I am calling the page with a #bookmark and have it smoothly scroll down to the relevant position once the page has completed loading. I don't know if this is a possibility or not?
This is the version of Smooth-Scroll that I'm using:
https://github.com/kswedberg/jquery-smooth-scroll
I'm still relatively new to jQuery so I may be overlooking something obvious.
Ajma's answer should be sufficient, but for completeness:
alert(location.hash)
Edit: a more complete example:
// on document.ready {
if (location.hash != '') {
var a = $("a[name=" + location.hash.substring(1) + "]");
// note that according to w3c specs, the url hash can also refer to the id
// of an element. if so, the above statement becomes
// var a = $(location.hash);
if (a.length) {
$('html,body').animate({
scrollTop: $(a).offset().top
}, 'slow');
}
}
// }
It's possible, you want to put a call into the smooth scroll function when the page is finished loading. in jQuery, it's using $(document).ready(function () { your code } );
You'll need to put something in to parse your url to extract the #bookmark and then call the smooth scroll.

HTML and jQuery anchoring

Whenever the url contains the div id, it would obviously go down to the div when the URL has:
http://domain.com.faq.php#1
<div id="1">Bla bla bla</div>
But what I like is to have same feature of Stackoverflow, when you click on an answer in your messages, it will scroll down to the page and has that fadeOut effect on the answer.
How do I do this?
Animation to a valid anchor destination cannot be animated on page load that I know of since the browsers will default to scrolling the user down the page to the anchor. For in-page links, you can hijack the anchor links and animate.
However, on new page loads like on SO, you will notice the page does not animate down, but just scrolls down, though the box does animate a color. This is how you could do it in jQuery. Be sure to include the color plugin if you want to animate background-colors.
<script src="js/jquery.color.js"> </script>
<script type="text/javascript">
$(window).load(function(){
var hash = window.location.hash;
if(hash){
$(hash).css('backgroundColor', '#AA0000')
.animate({backgroundColor: '#FFFFFF'}, 200);
}
});
</script>
You can use DOMReady instead of load, but it might try to run your animation too soon, and the user will miss it.
If you only wanted to animate div's with a specific class, you can add a filter to your find:
$(hash).filter('.my_div').css ...
Use:
event.preventDefault();
For example:
$('li.share a').click(function(ev) {
ev.preventDefault();
var link = ev.target.href;
var id = link.substring(link.indexOf("#") + 1);
$('#' + id).fadeOut();
});
StackOverflow uses anchors as well. The post you're currently reading is:
HTML and jQuery anchoring
It's simply <a name="anchorName"></a>
at the address bar: [urlToPage]#anchorName
Now, to get the fade effect [in pure JS w/o frameworks]
Set the div.style.opacity = 0;
var intervalId = setInterval( function(){
if( (div.style.opacity+= 0.1) >= 1) clearInterval(intervalId);
}, millisecondInterval);
The clearInterval part isn't necessary, since once opacity goes above 1, browser won't render differently [although the number keeps adding...]

Categories