Why is document.body not working on my subpages? - javascript

Background
I've created a simple workaround to get a fixed background to work on iPad and iPhone devices, i.e creating an empty div just after the body tag with position:fixed rather than background-attachment:fixed which these devices doesn't support. All variations on the body element I've tried, like pseudo ::before is not working on these devices. An empty div solves this.
Problem
My script below works perfectly on my main page ('Home'/'Start'). But I also have other pages like 'Contact' and such, sharing the same 'global' head tag where the script lies, where it doesn't work (the div simply doesn't show up). I would expect this to add a div after each body element, regardless of which page is loaded... Also, I'm using window.onload as I can't manually add the script after the body tag. Each subpage body tag has its own id but why would that matter? What am I missing?
window.onload = function FixedBg() {
var body = document.body;
var bgDiv = document.createElement('div');
bgDiv.className = "fixedBackground";
body.insertAdjacentElement('afterbegin', bgDiv);
}
I don't have access to manually add divs directly into the DOM which obviously would have been the approach otherwise, hence the JavaScript...

As was suggested in the comments above by #ProfessorAbronsius and #TheFool, using DOMContentLoaded and an event listener did the trick! Thank you

Related

Detect CSS Style Rendered

I have a application that loads CSS styles dynamic based on user preference. I use requirejs to load these like:
require(['css!dir/styles'], function(){ .... });
this works great but I don't want to show the screen until all the styles have fully initialized.
I've added a CSS class to the body of the page called hide-page and then remove that class when the callback occurs. Like:
setTimeout(function() { $(document.body).removeClass('hide-page'); }, 100);
but even with the settimeout, the page still loads jumbled until everything has initialized. I was thinking about doing a setInterval and checking if a particular style has been applied to a node like:
setInterval(function(){
if($(document.body).style('background'') === "#FFFFFF"){
$(document.body).removeClass('hide-page');
}
}, 10);
but thats kinda hackey. Is there a better solution anyone has to accomplish this?
You don't say how you're hiding the page content, but that could be the problem if you're using display:none.
Try visibility:hidden instead. This will allow the browser to allocate the space needed to construct the page, so you shouldn't see the jumbled FOUC.

Jump to iframe once it loads

Im looking for my webpage to jump to an iframe when someone click. I've found one solution which works pretty well which is this: http://jsfiddle.net/RGjCL/4/
<ul>
<li>
Class Name
</li>
</ul>
<script type="text/javascript">
function IFrameScroll(link){
window.myIframe.location=link;
window.location.hash='myIframe'
}
</script>
<IFRAME id = "myframe" onload = "setIframeHeight( this.id )" name="myIframe">
I've tried on my web and it partially works except for the fact it scrolls to the iframe before it loads so it doesn't goes that far to the bottom because once the iframe its loaded the page fully extends.
The web in question is the following: http://www.clavederock.com.ar -
The links are under the tabs "Quienes Somos" "Programacion" and "Archivo".
I hope i made myself clear so you can help me. Thanks in advance!
Try moving window.location.hash='myIframe' from the function IFrameScroll() to setIFrameHeight(), so you'll change the hash once the iframe have the desired size.
EDIT #3:
Since you need to wait until iframe is loaded in order to resize it and window.location.hash doesn't works the second time in chrome, you can try this:
<script type="text/javascript">
function IFrameScroll(link){
window.myIframe.onload = function() {
// this will ensure that the height will be updated after load
setIframeHeight('myIframe');
// This works on FF and IE, and let users to bookmark
window.location.hash='myIframe';
// and this will allow it to scroll the second time for chrome
document.getElementById('myIframe').scrollIntoView(true);
}
window.myIframe.location=link;
}
</script>
I really hope this solve your problem :)
Instead of jumping to the iframe, you could make a smooth scroll. This would give a little more time for the iframe to load after the link has been clicked.
Alternatively and probably more effectively, you could load the iframe with the rest of the page but make it invisible. Then you just need to show it when the user clicks the link
//load the page with the iframe hidden
//in css
#myIframe { visibility: hidden; }
//use jquery to make it visible when the user clicks the link
//you could do this with javascript if you don't want to import jQuery, but I find jQuery easier
$(document).ready(function() {
$('#myAnchorTagId').click(
function() {
$('myIframe').css('visibiliy', 'visible')
}
)
});

How to scroll the page with javascript before body load?

I'm trying to scroll the page 50px before body load. But it always waits for body load before running the code.
I'm not quite sure what's the reason, I seem to remember running as they are parsed.
I tried with both, jquery and plain javascript, this is my code:
$(document).scrollTop('50');
window.scrollBy(0,50);
How do I make it work before body load?
there is no body when you are calling the event so nothing would happen
one way around to this is that set the height of body so some constant number
and add onLoad event on the body tag
<script>
SomeFunction(){
//scrollNow
}
</Script>
<body onLoad="SomeFunction()" style="height:500px;"></body>
Found one working solution, maybe somebody will find cleaner one.
This can scroll the page even before the onload:
document.writeln(' ');
document.body.style.height = '5000px';
$(window).scrollTop(50);
Test script here.
1. Create css offset class and assign to the body
.offset{
margin-top:-500px;
}
So that body will be loaded with 500px offset from top
2. Then add following code to the body
<body class="offset" onLoad="window.scroll(0, 150)">
3. then using jquery, remove offset class when page is loaded
$(document).ready(function(){
$(".row").removeClass("offset");
});
This will work http://www.frameinn.com/thatisuday/about

Remove javascript tags from header using javascript

Suppose I have a main page that uses an iframe object as a buffer to load an external page from the same domain (for security reasons).
I chose this method because XMLHttpRequest is not able to parse from string external xhtml content in all browsers.
After the content has been loaded in the iframe, I "steal" it's content using the "contentDocument" property and then append all the css styles and script-tags to the parent's header and eventually delete the iframe (note that CSS and scripts are inline in the second document, so no external links at all).
Now everything works great - I can call the new javascript functions and css works as well.
My question is: I am able to manage removing the newly appended css styles, but with javascript does not work. Is there any solution to remove the header's newly added script tags from within the same document?
I even tried this in desperation (css vanishes, javascript still remains...)
function emptyheader()
{
/* var container = document.getElementById("container"); */
var header = document.getElementsByTagName('head')[0];
/* styles = header.getElementsByTagName('style'); */
/* scripts = header.getElementsByTagName('script'); */
while(header.hasChildNodes())
header.removeChild(header.firstChild);
}
I am not shore I understand what you mean. But here is an example of how you can add and then remomve a script (as far as I know it is okey to add script tag to body).
<script>
function addAndRemoveScript() {
var a = document.createElement("script");
a.src = "yourscript.js";
document.body.appendChild(a);
document.body.removeChild(document.body.getElementsByTagName("script")[0])
document.body.removeChild(document.body.getElementsByTagName("script")[0])
}
window.onload = addAndRemoveScript();
</script>

Remove background image on image load

I'm loading image tags via AJAX and inserting them with the conventional .html(content) function in jQuery alongside a bunch of other HTML. However, this question still applies if you're loading a page from scratch. Now, I have a background image placeholder to be put there while the image loads. I want this background image to go away when the image loads.
Problem:
If I attach a conventional .load(function) event listener, I am concerned that the image might load before the hook is applied (putting the hook in a small JS <script> right after the image instead of in a $(function(){}) block might help a bit). I have yet to encounter such behaviour, but I know of nothing in the specification that prevents this from happening (since the image tag ought to be fully parsed before the hook is applied).
My current solution. Put the command in an inline onload= property within the image tag.
Is there a better way?
Up until a week or so ago I would have been lost too. Thankfully this answer to another question will help you out:
Basically put this in $():
$(function(){
var img = $("#idofimage").load(function () {
/* your magic to swap out placeholder */
});
if (img[0].complete) {
// Trigger the load handler if the image
// is already loaded
img.trigger('load');
}
});
You don't need jQuery for this, you can do it with CSS.
.my-img-loader-class { background:url('placeholder-or-progress'); }
Or if you don't want to change your HTML:
#container img { background:url('placeholder-or-progress'); }
To show placeholders while images are loading in a specific div.
The way it works is the image element will show the placeholder image as its background, and when the src loads it will appear above the placeholder, so as to replace it nicely.

Categories