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
Related
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.
I know this question won't be well received but I searched far and long and can't find anything, probably not using the right keywords.
I own an online radio station and I want to create a js player that once added to a website will stay in the header on all the domains of the site. I first saw this thing on a tumblr music player(http://scmplayer.net/) , you would add their code to your page and once opened the player will stay as a header even if you browse to other sub-pages of your blog.
I'm searching for this to use in forums, where you change your page so often you can't listen to anything using a built-in radio player.
I found a similar solution by using a button that opens a really small pop-up with the player, but I'd like to know if it's possible to do what I want, and how.
Even a right link, query or term to search for would help me greatly, I don't want someone to do this for me, just point me in the right way.
Edit::
Here's some stuff I forgot to mention. I'm trying to build a code users can just copy paste into their website and have it work.
If it was only for me, I wouldn't be here, since I went trough iframes and jquery to load content too(see www.r4ge.ro).
I can't expect other people to tamper with their website only to embed my radio there, and I can't iframe their site content and add my radio as an index because that would ruin google ranking and indexing.
There are multiple ways of doing this, here goes one!
First thing, I'd personally use backbone.js - backbone.js allows you to create 'partial' views that can be updated independently of another. For your scenario, it seems ideal to create a header view and then a content view.
Both the header and the content could have their own logic, and update at separate times that you specify and under your control.
Take a look at http://backbonetutorials.com/why-would-you-use-backbone/ to get started. prepare yourself ample time to do a lot of reading and following tutorials. Backbone takes time to ramp up on, but once you get it, you'll be making some awesome apps!
You basically have three options:
The one you found, opening a really small pop-up (perhaps with just the media controls visible), so that when the user navigates, it isn't affected by the page being torn down.
The same thing using frames.
The same thing using ajax to load content when navigating instead of actually navigating.
As you didn't like #1 much, let's look at #2, then come back to #3.
When the use opens the player, you'd really be going to a page with the player and a very large iframe with the rest of the content:
<!doctype html>
<html>
<head>
<!-- ... -->
</head>
<body>
<!-- player here -->
<iframe class="main" src="main.html"></iframe>
</body>
</html>
You'd use CSS to make that as seamless as you could. To make it linkable, you could use a large fragment in the URL which is the URL of the page that should go in the frame, e.g.:
http://example.com/#forum.html§ion=23
When your main page loads, you grab the fragment, and use it as the src on the iframe.
You can listen for navigation events on the iframe and update the hash fragment on the main window, so that bookmarks work, and/or have JavaScript on each page of your site that might be navigated to that tells the container page (parent) what its URL is.
#3 is similar to #2 except that rather than letting navigation happen the normal way, you load everything via ajax as the user clicks around, loading it into (say) a main content div rather than an iframe. This can also use hash fragments to ensure that it's fully linkable/bookmarkable, etc., but requires that all links in the pages loaded get rewritten so they update the hash fragment rather than the main URL instead.
#2 and #3 (and #1) all have their advantages and disadvantages. #1 is probably the least work. #2 probably comes in second, then #3, but I could have those backward.
Here's a quick and dirty version of #2 that polls for hash updates so that the pages loaded in the frame don't have to know anything about this at all. Note that all you'd have to give to the other people is the page; their pages remain the same. If they're concerned about page rank, they'll want to include the canonical URL of their pages in the markup.
withplayer.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<style>
html, body {
padding: 0;
margin: 0;
}
html {
height: 100%;
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
height: 100%;
position: relative;
}
div.player {
height: 30px;
padding: 2px;
}
iframe.content {
border: none;
position: absolute;
top:30px;
width: 100%;
/*bottom: 0px; Sigh, this works on elements other than iframe, see 'resize' JavaScript below */
}
</style>
</head>
<body>
<div class="player"></div>
<iframe class="content"></iframe>
<script>
(function() {
// Fill in our "player"
var dt = new Date().toISOString();
document.querySelector(".player").innerHTML =
"This div is our pretend player: The div was loaded on " +
dt.substring(0, 10) + " at " + dt.substring(11, 19) + ".";
// Get the iframe
var content = document.querySelector(".content");
// Listen for hash changes
window.onhashchange = loadContent;
// Load any initial hash we have
loadContent();
// Get our current hash, without the leading #
function getHash() {
return location.hash.replace(/^#/, '');
}
// Get the hash equivalent of the current content in the content iframe
function getContentHash() {
var loc, hash;
loc = content && content.contentWindow && content.contentWindow.location;
hash = loc && loc != "about:blank" ? loc.pathname + loc.search + loc.hash : undefined;
return hash;
}
// Load the content for the current hash
function loadContent() {
// If we have an initial hash, apply to the iframe
var hash = getHash();
if (hash) {
content.src = hash;
}
}
// Poll for changes to the frame's location, update our hash if
// it doesn't match
setInterval(pollContent, 100);
function pollContent() {
var newHash;
newHash = getContentHash();
if (newHash !== undefined && newHash !== getHash()) {
location.hash = "#" + newHash;
}
}
// Stoopid iframes won't stick to the bottom, have to resize their height
resize();
window.onresize = resize;
function resize() {
content.style.height = (window.innerHeight - 30) + "px";
}
})();
</script>
</body>
</html>
My site has a parent page with 2 iframes on it. Currently I have it all running how I would like, with the exception that using the browser back button only changes the content of 1 of the 2 iframes. I'm trying to make a check inside the child frames so that the correct content page is loaded in the sister iframe. My iframes are leftiframe and rightiframe.
This is the code I have at the moment (not working):
<script type="text/javascript">
window.onload = function() {
if(/iframe1.html/.test(parent.leftiframe.location.href))
{
}
else
{
parent.leftiframe.location.href="iframe1.html";
}
}
</script>
If I change it so that it is reading the string from within the current window, like so:
if(/iframe2.html/.test(window.location.href))
then it has no problems reading the URL and will change the URL of the sister iframe without issue. Why does parent.leftiframe not work in place of window?
Thank you!
Try using this instead:
<script type="text/javascript">
window.onload = function() {
if(/iframe1.html/.test(parent.leftiframe.contentWindow.location.href))
{
}
else
{
parent.leftiframe.contentWindow.location.href="iframe1.html";
}
}
</script>
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>
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!!