Stop page from scolling up on link click - javascript

Fixed! Solution found on the end of this question
I've been working on a website where I have a Index page and a Info page. When you scroll down in the Index page and click the link to the Info page I want the Info page to open on the same position as the Index page was scrolled to.
I read about ScrollSneak and several similar questions and explanations here on Stackoverflow but could net get it to work for myself. I am quite a noob on javascript and am only beginning to learn how to use it. Can someone perhaps give me a example how to actually apply it to a link? I seem to fail to see what element actually links it to the actual link.
Code I found and applied below (gist link removed cause I have too low reputation to add more than 2 links xD check ScrollSneak for the file)
<!DOCTYPE html>
<html>
<head>
<!--i'm using jquery too -->
<script type="text/javascript" src="path/to/jquery.js"></script>
<!-- include scroll_sneak.js -->
<script type="text/javascript" src="path/to/scroll_sneak.js"></script>
<!-- now activate scroll sneak -->
<script type="text/javascript">
$(document).ready(function(){
var sneaky = new ScrollSneak(location.hostname);
// you want to prevent scrolling when form #my-form is submitted
document.getElementById('my-form').onsubmit = sneaky.sneak;
// or maybe you want to prevent scrolling whenever any link within
// a list-option is clicked:
$('li a').each(function(){
// note the use of 'this' instead of '$(this)', because we
// want the raw element, not the jQuery object
this.onclick = sneaky.sneak;
});
});
</script>
</head>
<body>
<img src="IMG/info_inactive.png" onmouseover="this.src='IMG/info_active.png'" onmouseout="this.src='IMG/info_inactive.png'" />
...
</body>
</html>
Overlay code Im using right now
<script>
window.addEventListener("load", function(){
var load_screen = document.getElementById("load_screen");
document.body.removeChild(load_screen);
});
</script>
SOLUTION!
I was able to find a working code on this forum topic, the submitter found it on another topic on Stackoverflow. Without futher ado, the code!
First you need a read-cookie function. Put this in the section of your page:
<script language="JavaScript">
function readCookie(name){
return(document.cookie.match('(^|; )'+name+'=([^;]*)')||0)[2]
}
</script>
Next you modify the body tag as follows:
<body onScroll="document.cookie='ypos=' + window.pageYOffset" onLoad="window.scrollTo(0,readCookie('ypos'))">
NOTE! Tested in Chrome, Firefox and Safari. "Surprisingly" this does not work in IE, but who uses IE anyway? -_-
Thanks everyone for helping me out, it is much appreciated ;)

If Taffer's solution is not working for you, you can try adding the scroll position as a get param.
(Disclosure: I do not use jquery, I prefer Mootools, but this should work)
Add an identifying class to each link you would like to scroll on the new page:
<a class="linkandscroll" href="info.html">link</a>
Then on each page, add this:
<script>
/* Method to return get params from url
thanks to: http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
*/
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
return false;
}
/* Method to link and set scroll get param */
function linkAndScroll(element){
/* get link element's href attribute */
var href = element.attr('href');
/* get curent scroll position */
var currentScroll = $('body').scrollTop();
/* create new url */
var url = href + '?scrollto=' + currentScroll;
/* change page location */
window.location.href = url;
}
/* on doc ready */
$(document).ready(function(){
/* loop through each scrolling link */
$('a.linkandscroll').each(function(){
/* add click event to call linkAndScroll method */
$(this).on('click', function(){
linkAndScroll($(this));
return false;
});
});
/* If scroll param is set on this page, do scroll now */
var scroll = getUrlParameter('scrollto');
if(scroll){
window.scrollTo(0, scroll);
}
});
</script>

I don't think you'll need scrollsneak, it's way more simple than that.
There are several solutions depending upon what you want, either JSRef:
<script>
function scrollWin() {
window.scrollTo(500, 0);
}
</script>
(expanded upon here: http://www.w3schools.com/jsref/met_win_scrollto.asp )
The space where it says 500 is to scroll on the X-axis(left and right), the 0 is for the Y-axis(up and down). You just change the numbers until you find the position you like.
And to make it go to another page and then execute this, you could make a script that takes some parameters like the URL of the link and specific position(or value of the element the link is contained within), and puts them into use, like so:
<script>
function linkAndScrollTo(theURL, xPos, yPos){
window.location.href = theURL;
window.scrollTo(xPos, yPos);
}
<script>
Or if you want it to scroll to a certain element in general, you can add an ID to the elements that ought to be "scrollable to", and then have the link lead to that ID on the next page. For example:
<div>
SomethingSomethingDarkside
</div>
There are probably more, I hope this answered the question.

Related

How to automatically attribute links with nofollow, only for a SPECIFIC html element in a webpage?

Some time ago I found this good old No Follow script, to add a nofollow attribute to hyperlinks. However, I dont want this script to be a site-wide thing! I just want hyperlinks inside a certain html element (say for example <article> ...</article>) to be attributed with a nofollow. How can one adapt the below script to achieve this?
<script type='text/javascript'>
var a = $(this);
var href = a.attr('href');
$(document).ready(function(){
$("a[href^='https://']").each(function (){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr('rel', 'nofollow');
}
});
});
</script>
Note: in essence, my question is the exact opposite of this question:
"Nofollow for the whole page?"

JavaScript Scroll Script - Fires in test, not on dev site

My script to replace the logo upon scroll works here in the test 'http://jsfiddle.net/timsalabim/opek5mtz/`
<!-- Logo Scroll -->
var img = document.querySelector('.logo_h__img img'); // get the element
img.dataset.orig = img.src; // dataset
document.addEventListener('scroll', function (e) { // add the event listener
if (document.body.scrollTop > 0) { // check the scroll position
img.src = img.dataset.scroll; // set the scroll image
} else {
img.src = img.dataset.orig; // set the original image back
}
});
It does not work when implemented exactly the same way in to the website, I think I have tested it correctly and it is firing too....
I put the script in to my site in the <head> </head> tags located in the header.php file (Wordpress website) inside these tags:
<script type="text/javascript"> </script>
I also didn't forget to add this section the image tag:
data-scroll="http://"
Is it possible that the navigation is set up in a way that the logo which is nested next to it doesn't recognise a scroll?
**** UPDATE ****
Here is my dev site: http://dev.greenlabit.com.au/Test/
I tried some other JS and got it to work!
It stopped functioning when the fixed navigation bar was in use.
Thank you for all of your help.

Unable to persist header like Facebook

I am currently a beginner JavaScript learner. I was trying some special code logics found on various top websites like Facebook. One of them I found here: How does Facebook keep the header and footer fixed while loading a different page?. But I am unable to execute it properly. Following is my code:
<html>
<head>
</head>
<body>
<div id="header">TEST HEADER
SAMPLE</div>
<p>OUTSIDE</p>
<script type='text/javascript'>
var header = document.getElementById('header');
var headerLinks = header.getElementsByTagName('a');
for (var i = 0, l = headerLinks.length; i < l; i++) {
headerLinks[i].onclick = function () {
var href = this.href;
//Load the AJAX page (this is a whole other topic)
loadPage(href);
//Update the address bar to make it look like you were redirected
location.hash = '#' + href;
//Unfocus the link to make it look like you were redirected
this.blur();
//Prevent the natural HTTP redirect
return false;
}
}
</script>
</body>
</html>
Please tell me what I am doing wrong?
Actually the motive of my code is not just to persist header on a page but also when navigating to other page. The header should not reload when navigated to other page.
Solution from the answer by Bill F.:
Forgot to define loadPage() function:
<script type="text/javascript">
function loadPage() {
document.getElementById("content").innerHTML = '<object type="type/html" data="sample2.htm" ></object>';
}
</script>
You haven't defined the function loadPage is what you're doing wrong. Presumably, that function will use AJAX to retrieve a page's contents, whether in JSON, HTML, XML, CSV, whatever.
You can keep the position of a div fixed even while scrolling using position:fixed
#header
{
position:fixed;
}
i have managed to do it properly all you need to do is create 2 seperate container divs,1 for the nav bar(which you want to remain) and 2 for the content which you want changed then simply retrieve the data from an external page
CODE representation
<div class="container_for_persistent_nav-bar">
</div>
<div class="container_for_divs_that_are_not_persistent">
</div>
then just bind a click event to links that will,1.on click clear the div container for NON_PERSISTENT DIVS and then,2.load the divs from a separate page

Page scrolling to every hash mark on page?

I have a PHP page that loads external content using other PHP files. I'm using include so it should be pretty simple. I had a scrollTo function (below) that I removed. However, ever since I did that when I reload the main page I can see in the URL that it is scrolling to every hash mark really quick, ending in the last section.
I really don't know what script may be causing that. I used Chrome Elements but I don't see anything.
I've been trying to figure this out for the past two hours so I really need another set of eyes to help me figure out where is this coming from. So please just take a quick look.
Here is the live test page that's going crazy now.
Test page
Here is the JS code I had originally, and then removed
$().ready(function(){
var currentAnchor1 = null;
//Check if it has changes
if(currentAnchor1 != document.location.hash){
currentAnchor1 = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor1){
query1 = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits1 = currentAnchor1.substring(1).split('&');
//Get the section
var page1 = splits1[0];
delete splits1[0];
var query1 = "page=" + page1;
}
//Send the petition
$.scrollTo( document.location.hash, 500, { easing:'elasout' });
}
});
This is coming from your PHP page. 4100.php is outputting inline JavaScript.
You can't use <!-- for block comments in JavaScript so your window.location calls are indeed still happening. (For multiline comments in JavaScript, surround the lines with /* and */ instead.)
Line 2485:
<script type="text/javascript">
<!--
window.location = "http://www.period3designs.com/tmss/l1/terminals/4100.php#4100errors"
//-->
</script>
Line 4779:
<script type="text/javascript">
<!--
window.location = "http://www.period3designs.com/tmss/l1/terminals/4100.php#4100guides"
//-->
Line 5319:
<script type="text/javascript">
<!--
window.location = "http://www.period3designs.com/tmss/l1/terminals/4100.php#4100howto"
//-->
</script>
Line 5393:
<script type="text/javascript">
<!--
window.location = "http://www.period3designs.com/tmss/l1/terminals/4100.php#4100functions"
//-->
</script>
Line 5467:
<script type="text/javascript">
<!--
window.location = "http://www.period3designs.com/tmss/l1/terminals/4100.php#4100menus"
//-->
</script>

How can we keep OpenX from blocking page load?

We're using OpenX to serve ads on a number of sites. If the OpenX server has problems, however, it blocks page loads on these sites. I'd rather have the sites fail gracefully, i.e. load the pages without the ads and fill them in when they become available.
We're using OpenX's single page call, and we're giving divs explicit size in CSS so they can be laid out without their contents, but still loading the script blocks page load. Are there other best practices for speeding up pages with OpenX?
We load our ads in iframes to avoid the problem you're having. We size div and the iframe the same, with the iframe pointing to a page which just contains the ad snippet (you can pass the zone and other required options as parameters to that page).
cheers
Lee
We lazy-load OpenX's code. Instead of putting the single-page call at the top of the page, we put it at the bottom. After the page has loaded, the call will get the banner data and a custom code will add the correct banners in the correct zones.
The code below requires a proper DOM. If you have jQuery, DOMAssistant, FlowJS, etc, the DOM should be fixed for you.
This code will work with normal banners with images, flash, or HTML content. It may not work in some cases like when using banners from external providers (adform, etc). For that you may need to hack the code a bit.
How to use it?
add your SinglePageCall code towards the end of your HTML code
add this code under the SPC code.
after half a second or so, your OpenX code should be ready, and the code below will put the banners within the specified DIVs.
Oh, yeah, you need to add to your HTML code some DIVs as place holders for your banners. By default I have these banners set with CSS class "hidden" which totally hides the DIVs (with visibility, display, and height). Then, after the banner in a given DIV is successfully loaded, we remove the hidden class and the DIV (and the banner within) become visible.
Use at your own risk! :) Hope it helps
(function(){
if (!document || !document.getElementById || !document.addEventListener || !document.removeClass) {
return; // No proper DOM; give up.
}
var openx_timeout = 1, // limit the time we wait for openx
oZones = new Object(), // list of [div_id] => zoneID
displayBannerAds; // function.
// oZones.<divID> = <zoneID>
// eg: oZones.banner_below_job2 = 100;
// (generated on the server side with PHP)
oZones.banner_top = 23;
oZones.banner_bottom = 34;
displayBannerAds = function(){
if( typeof(OA_output)!='undefined' && OA_output.constructor == Array ){
// OpenX SinglePageCall ready!
if (OA_output.length>0) {
for (var zone_div_id in oZones){
zoneid = oZones[zone_div_id];
if(typeof(OA_output[zoneid])!='undefined' && OA_output[zoneid]!='') {
var flashCode,
oDIV = document.getElementById( zone_div_id );
if (oDIV) {
// if it's a flash banner..
if(OA_output[zoneid].indexOf("ox_swf.write")!=-1)
{
// extract javascript code
var pre_code_wrap = "<script type='text/javascript'><!--// <![CDATA[",
post_code_wrap = "// ]]> -->";
flashCode = OA_output[zoneid].substr(OA_output[zoneid].indexOf(pre_code_wrap)+pre_code_wrap.length);
flashCode = flashCode.substr(0, flashCode.indexOf(post_code_wrap));
// replace destination for the SWFObject
flashCode = flashCode.replace(/ox\_swf\.write\(\'(.*)'\)/, "ox_swf.write('"+ oDIV.id +"')");
// insert SWFObject
if( flashCode.indexOf("ox_swf.write")!=-1 ){
eval(flashCode);
oDIV.removeClass('hidden');
}// else: the code was not as expected; don't show it
}else{
// normal image banner; just set the contents of the DIV
oDIV.innerHTML = OA_output[zoneid];
oDIV.removeClass('hidden');
}
}
}
} // end of loop
}//else: no banners on this page
}else{
// not ready, let's wait a bit
if (openx_timeout>80) {
return; // we waited too long; abort
};
setTimeout( displayBannerAds, 10*openx_timeout );
openx_timeout+=4;
}
};
displayBannerAds();
})();
OpenX has some documentation on how to make their tags load asynchronously:
http://docs.openx.com/ad_server/adtagguide_synchjs_implementing_async.html
I've tested it, and it works well in current Chrome/Firefox.
It takes some manual tweaking of their ad code. Their example of how the ad tags should end up:
<html>
<head></head>
<body>
Some content here.
Ad goes here.
<!-- Preserve space while the rest of the page loads. -->
<div id="placeholderId" style="width:728px;height:90px">
<!-- Fallback mechanism to use if unable to load the script tag. -->
<noscript>
<iframe id="4cb4e94bd5bb6" name="4cb4e94bd5bb6"
src="http://d.example.com/w/1.0/afr?auid=8&target=
_blank&cb=INSERT_RANDOM_NUMBER_HERE"
frameborder="0" scrolling="no" width="728"
height="90">
<a href="http://d.example.com/w/1.0/rc?cs=
4cb4e94bd5bb6&cb=INSERT_RANDOM_NUMBER_HERE"
target="_blank">
<img src="http://d.example.com/w/1.0/ai?auid=8&cs=
4cb4e94bd5bb6&cb=INSERT_RANDOM_NUMBER_HERE"
border="0" alt=""></a></iframe>
</noscript>
</div>
<!--Async ad request with multiple parameters.-->
<script type="text/javascript">
var OX_ads = OX_ads || [];
OX_ads.push({
"slot_id":"placeholderId",
"auid":"8",
"tid":"4",
"tg":"_blank",
"r":"http://redirect.clicks.to.here/landing.html",
"rd":"120",
"rm":"2",
"imp_beacon":"HTML for client-side impression beacon",
"fallback":"HTML for client-side fallback"
});
</script>
<!-- Fetch the Tag Library -->
<script type="text/javascript" src="http://d.example.com/w/1.0/jstag"></script>
Some other content here.
</body>
</html>
Following #Rafa excellent answer, i'm using this code to invoke OpenX banners after the page loads. I'm using jquery as well and had to add a new replace call for the "document.write" that flash banners use, and replacing it with "$('#"+ oDIV.id +"').append" instead. I'm using a custom "my_openx()" call, to replace "OA_show()". My banners area called by the zone_id and are wrapped inside a div, like this:
<div id="openx-4"><script>wm_openx(4);</script></div>
It's working :)
<script type="text/javascript">
$is_mobile = false;
$document_ready = 0;
$(document).ready(function() {
$document_ready = 1;
if( $('#MobileCheck').css('display') == 'inline' ) {
$is_mobile = true;
//alert('is_mobile: '+$is_mobile);
}
});
function wm_openx($id) {
if($is_mobile) return false;
if(!$document_ready) {
setTimeout(function(){ wm_openx($id); },1000);
return false;
}
if(typeof(OA_output[$id])!='undefined' && OA_output[$id]!='') {
var flashCode,
oDIV = document.getElementById('openx-'+$id);
if (oDIV) {
// if it's a flash banner..
if(OA_output[$id].indexOf("ox_swf.write")!=-1) {
// extract javascript code
var pre_code_wrap = "<script type='text/javascript'><!--// <![CDATA[",
post_code_wrap = "// ]]> -->";
flashCode = OA_output[$id].substr(OA_output[$id].indexOf(pre_code_wrap)+pre_code_wrap.length);
flashCode = flashCode.substr(0, flashCode.indexOf(post_code_wrap));
// replace destination for the SWFObject
flashCode = flashCode.replace(/ox\_swf\.write\(\'(.*)'\)/, "ox_swf.write('"+ oDIV.id +"')");
flashCode = flashCode.replace(/document.write/, "$('#"+ oDIV.id +"').append");
// insert SWFObject
if( flashCode.indexOf("ox_swf.write")!=-1 ) {
//alert(flashCode);
eval(flashCode);
//oDIV.removeClass('hidden');
}// else: the code was not as expected; don't show it
}else{
// normal image banner; just set the contents of the DIV
oDIV.innerHTML = OA_output[$id];
//oDIV.removeClass('hidden');
}
}
}
//OA_show($id);
}
</script>
I was looking for this to load advertising from my openX server only when the advertising should be visible. I'm using the iFrame version of openX which is loaded in a div. The answer here put me on my way to solving this problem, but the posted solution is a bit too simple. First of all, when the page is not loaded from the top (in case the user enters the page by clicking 'back') none of the divs are loaded. So you'll need something like this:
$(document).ready(function(){
$(window).scroll(lazyload);
lazyload();
});
also, you'll need to know what defines a visible div. That can be a div that's fully visible or partially visible. If the bottom of the object is greater or equal to the top of the window AND the top of the object is smaller or equal to the bottom of the window it should be visible (or in this case: loaded). Your function lazyload may look like this:
function lazyload(){
var wt = $(window).scrollTop(); //* top of the window
var wb = wt + $(window).height(); //* bottom of the window
$(".ads").each(function(){
var ot = $(this).offset().top; //* top of object (i.e. advertising div)
var ob = ot + $(this).height(); //* bottom of object
if(!$(this).attr("loaded") && wt<=ob && wb >= ot){
$(this).html("here goes the iframe definition");
$(this).attr("loaded",true);
}
});
}
Tested on all major browsers and even on my iPhone, works like a charm!!

Categories

Resources