Delay Javascript or div until page load - javascript

I've been looking around for a solution, trying a few suggestion but none seem to work for the script I've got or don't understand the solutions properly, so hoping there is someone out there that can help.
In the head tag I've got the javascript script below. It slides the 8th div on the page up from the bottom into the page. However, when you visit the page you get a quick glance of the contents of this div (a block of text) in its end position, before it slides into the page. How do I get rid of this quick preview and get the text block div to slide in when the main image is loaded?
Link to site: http://www.estilosalon.com.au/estilo-salon-philosophy2.html
<script type="text/javascript">
i=-700;
var c;
function f(){
c=setInterval(function(){inv()},5)
}
function inv()
{
if(i!=0)
{
i+=5;
document.getElementsByTagName("div")[8].style.bottom=i+"px";
}
else
{
clearInterval(c);
document.getElementsByTagName("button")[0].parentNode.removeChild(document.getElementsByTagName("button")[0]);
}
}
</script>
Thanks in advance!

You could try the following:
Add a class to your <html> tag as a fallback when there is no js:
<html xmlns="http://www.w3.org/1999/xhtml" class="no-js">
Replace the no-js class with js class by placing this code before i=-700; line
var html = document.documentElement;
html.className=html.className.replace(/\bno-js\b/,'') + 'js';
Add this to your style sheet
html.js #text_box_philosophy{
bottom: -700px;
}

You can attach a function to the body's load event <body onload="f()"> and set div[8] to display: none in your css and then set it to document.getElementsByTagName("div")[8].style.display = "block" in f().
However, I would strongly consider using jQuery and the $().animate function to animate the div, assigning the div an id (if you add more div elements before it, your code will break), and using jQuery's $(document).ready() function to fire the initial code rather than using <body onload="">. Taking these steps will help your code perform uniformly across multiple browsers.

Related

Need "document.write" to only write inside a specific element, not overwrite the whole page [duplicate]

I'm very new with javascript.
I'm trying to create a tag using document.write (with Wordpress) to add a style that hides images before they are preloaded. I've had to resort to writing a Javascript style to hide the images before they are loaded via CSS. I don't want to actually write it into the CSS file incase the user has Javascript disabled and then the images would never show.
I'm trying to get this code to work:
jQuery(function($) {
document.write('<style type="text/css"> .preload img { display: none; } </style>');
$('#body-wrap').preloadThis();
});
But, it is just overwriting the whole page and making it go blank. How can I stop this? I want to add the tag to the without removing the page. Tried using 'return', no luck.
Sorry, I'm a novice. Thanks in advance.
Using document.write() after the page has finished loading implicitly calls document.open(), which creates a new page. You should generally avoid document.write() and stick to proper DOM creation techniques, or use jQuery's shorthand creation methods:
jQuery(function($) {
$('<style type="text/css"> .preload img { display: none; } </style>')
.appendTo("head");
$('#body-wrap').preloadThis();
});
I'm assuming you can't edit the HTML or CSS files that are loaded by the page to include this rule? If that's the case, and you want these styles applied before the page finishes loading, take `document.write()` out of the jQuery ready handler:
// write() before the document finishes loading
document.write('<style type="text/css"> .preload img { display: none; } </style>');
jQuery(function($) {
$('#body-wrap').preloadThis();
});
This will write the <style> tag immediately after the currently executing <script> tag. Hopefully, this is in your <head> element as <style> is invalid anywhere else, although all browsers should parse it OK either way.
You don't need to add <style> tag, you can just hide them with jQuery:
jQuery(function($) {
$('.preload img').hide();
$('#body-wrap').preloadThis();
});
Don't know how your preloadThis() function works, but I guess it loads images and removes .preload class from img container. If it indeed works like that, this code will not help you - images will stay hidden.

jQuery Mobile Scroll Events

Having issues with getting the scroll series of events to function (at all, not just as designed). Have been trawling through all articles, code suggestions and other help topics regarding this, but no-one can explain why this example doesn't work at all:
Basic page html:
<!DOCTYPE html>
<html>
<head>
<title>JQM Test</title>
<script src="/inc/jQuery/jquery-1.11.3.js"></script>
<script src="/inc/jQuery/mobile/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript">
var scroll = 0;
$(function() {
$(window).on('scroll',function(e) {
console.log("Scrolled - "+scroll);
scroll++;
});
});
</script>
</head>
<body>
Contents blah blah.
</body>
</html>
Ok so the inclusion files need substituting if you copy paste, and version may be differnet. Anwyays onto the behaviour. When I take out the jquery.mobile inclusion the script works as expected, logging scroll notes into the console whenever scroll position is altered.
When I include the jquery.mobile it fires once when the page loads and thats it. Have tried document/window changes in the jquery script section, scrollstart and scrollstop events. Even tried explicitly binding an even to the scroll using native javascript. Same result, all works fine without jqm inclusion, fails when I include the jqm.
Can someone explain to me why the JQM stuff breaks the scroll functions?
EDIT:
THe following JS functions have been attempted with the EXACT same result (function until JQM inclusion added)
$(document).on("scrollstart",function(){
****
$(document).on("scrollstop",function(){
****
$(window).on("scrollstart",function(){
****
$(window).on("scrollstop",function(){
****
$(document).scrollstart(function(){
****
$(document).scrollstop(function(){
****
$(window).scrollstart(function(){
****
$(window).scrollstop(function(){
****
window.onscroll=myFunction;
document.onscroll=myFunction;
window.attachEvent("scroll",myFunction,false);
document.attachEvent("scroll",myFunction,false);
Try this :
$(function() {
$(window).on('scroll',function(e) {
console.log("Scrolled - "+scroll);
window.scrollBy(100, 0); // for scroll horizontally.
});
});
With help from #FraserCrosbie turns out it was a bit of CSS I was ignoring: https://jsfiddle.net/nzwodyte/4/
The CSS was assigned to a [data-role=page]{ elements and had the height: 100% and position: relative tags.
Didn't realise that JQM was assigning data-role="page" to elements in my HTML without my declaration of said tags.
So for anyone with the same issues, check height and position CSS of your pages (from a debug point of view, not in the original DOM)

jQuery shows hidden content on refresh

I use this fancy little jQuery toggle on my site, works great. But now I have a little larger text area I want to hide, and therefore I've included it in another php file, but when the site opens\refreshes the content is briefly shown and then hidden? Have I done something wrong or does it simply not work right with includes in it ?
Show me?
<div class="content">
<?php include 'includes/test.php'?>
</div>
<script>
jQuery(document).ready(function() {
var par = jQuery('.content');
jQuery(par).hide();
});
jQuery('#toggleMe').click(function() {
jQuery('.content').slideToggle('fast');
return false;
});
</script>
Use css to hide it
.content{
display:none;
}
Also
var par = jQuery('.content');
is a jQuery object so don't need to wrap it again as
jQuery(par).hide();
Just use par.hide(); but in this case, when you will use css to hide the element, then you don't need this anymore.
That will happen. The document briefly shows all the HTML before executing the code in your ready handler. (It has nothing to do with the PHP include.) If you want an element hidden when the page loads, hide it using CSS.
#myElement {
display: none;
}
The toggle should still work correctly.
You just need to don't use jquery document ready function. just use style attribute.
Show me?
<div class="content" style="display:none">
<?php include 'includes/test.php'?>
</div>
<script>
jQuery(document).ready(function() {
jQuery('#toggleMe').click(function() {
jQuery('.content').slideToggle('fast');
return false;
});
</script>
If this information is sensitive/not supposed to be seen without access granted, hiding it with CSS will not fix your problem. If it's not, you can ignore all of this and just use CSS with a display: none property.
If the information IS supposed to be hidden:
You need to only load the file itself on-demand. You would request the data with AJAX, do a $('.content').html() or .append() and send the result back directly from the server to the browser using something like JSON.
You are using the "ready" function that meant it will hide the element when the document is ready (fully loaded).
You can hide it using css:
.contnet { display: none; }
how you render you site server side does not affect how the site is loaded on the browser, what affects it is how the specific browser chooses to load your javascript and html, what i would recommend is set the element to hidden with css, since that is applied before anything else. And keep you code as is, since the toggle will work anyways
You can also clean up the code a little bit.
<script>
$(document).ready(function(){
$('.content').hide();
$('#toggleMe').click(function(){
$('.content').slideToggle('fast');
});
});
</script>

jQuery function in pure javascript

I'm one of those people who never was bother to learn JavaScript and went straight for jQuery.
I'm writing simple script to hide everything till page is fully loaded - and because my jQuery is loaded after html/css/images I planning to put small script in the header.
So in jQuery it would be
$('body').css('display','none');
Pure JavaScript:
document.body.parentNode.style.display = 'none';
But than:
$(window).load(function() { $('body').css('display', 'block').fadeIn(3000); });
Has not animation? Why?
What I'm trying to do:
#1 hide everything(body) with javascipt till everything is loaded (there is no jQuery at this state as is being loaded at the end)
#2 show everthing(body) with animation of fadding (with jQuery - as is loaded at this state)
Any help much appreciated.
Pete
The equivalent to
$('body').css('display','none');
is
document.body.style.display = 'none';
$('body') selects the body element, but document.body.parentNode obviously selects the parent of body.
And shouldn't it be just
$('body').fadeIn(3000);
?
I asked because I assumed you already got the code working with only jQuery. But apparently you haven't, so again, it has to be $('body').fadeIn(3000); only, otherwise you make the element visible immediately and there is nothing to animate anymore.
See a demo: http://jsfiddle.net/fkling/Q24pC/1/
Update:
$(window).load is only triggered when the all resources are loaded. This could take longer if you have images. To hide the elements earlier, you should listen to the ready event:
$(document).ready(function() {
// still don't know why you don't want to use jQuery.
document.body.style.display = 'none';
});
or hide the elements initially with CSS
body {
display: none;
}
To make sure that users with disabled JavaScript can see the page, you'd have to add
<noscript>
<style>
body {
display: block;
}
</style>
</noscript>
in the head after you other CSS styles.
Update 2
Seems that setting the CSS property directly causes problems in some browsers. But using $('body').hide() seems to work: http://jsfiddle.net/fkling/JaLZU/
I'm not that clear on what your question really is, but if I'm on the right track you don't need the .css('display', 'block') part for the animation. Get rid of that, so it's just $('body').fadeIn(3000); and the animation should work fine.

Need help with Cross Browser Inconsistencies in overlay

RESOLVED
I found the issue and am sorry to say it is quite idiotic. On some pages there was an extra closing bracket after the script type=javascript. Apparently Chrome and Firefox ignore the issue but Safari and IE threw up display errors. Thank you to everybody for the excellent support and guidance on the matter. of note, i decided to go with the .show() method as it seemed most logical.
I have the following javascript snippet at the top of my page which validates 2 fields within a login form:
<script type="text/javascript">
$(function() {
$('#submit').click(function () {
$('#login_form span').hide();
if ($("input#user").val() == "") {
$("span#user").show();
$("input#user").focus();
return false;
}
if ($("input#pw").val() == "") {
$("span#pw").show();
$("input#pw").focus();
return false;
}
var overlay = $('<div id="overlay">');
$('body').append(overlay);
});
});
</script>
When a form is submitted (submit is clicked) the function is run which checks to make sure the 2 fields: pw and user have some content. If they do, it opens an overlay script to cover the screen. The function above sits at the top of my screen (in the head)
The CSS for the overlay is:
#overlay { background:#000 url(../images/loader.gif) center no-repeat; opacity:0.5; filter:alpha(opacity = 50); width:100%; height:100%; position:absolute; top:0; left:0; z-index:1000; }
In Chrome:
The function works well but the 'loading' image within the overlay does not show.
In Firefox:
Nearly the same as Chrome but the loading image DOES work if the javascript call is made at the bottom of the page.
In IE:
if the function stays in the head, my page is completely blank (though no server errors). Once I move to the bottom of the page, the loading image appears randomly and if it does, it is VERY slow in its animation.
perhaps I am doing something wrong but trying to build for all three browsers on something this simple is making me bonkers.
Any suggestions for improvement?
Thanks ahead of time.
UPDATE
First off thank you all for your suggestions so far. I have tried and number and get various results from each (as well as different results when run locally versus on our apache server).
One page in particular that seems to be of fury is this one:
https://www.nacdbenefits.com/myadmin/password-reset
In IE, the page just opens to a grey screen. I have updated the code to imbed the div id in the page itself and simply 'show' on a submit but apparently something else is catching a long the way.
UPDATE 2
Something else must be causing this to malfunction. When i strip the code even to:
<script type="text/javascript">
$(function() {
});
</script>
unless I move the code to the bottom of the page, IE just shows a dark screen with nothing there (no server errors again and no JS errors at page bottom).
I would have the overlay already existant in the page's HTML but hidden (display: none;), so that the background image is preloaded. Then, once my button is clicked, I would .show() it.
I think your code has a bug. I'm suprised Firefox manages to make something out of it. According to .append() you should pass it a string or an element. You're attempting to pass it a jQuery selector result (and a broken one at that). Remember, in jQuery $() is a function call! Compare your code (condensed):
$('body').append($('<div id="overlay">'));
with this (no $() call):
$('body').append('<div id="overlay" />');
or this (note closing the div tag):
$('body').append($('<div id="overlay" />'));
Have you considered having the overlay as part of your page's code, but simply display: none by default, and then simply .show()ing it when you want it to appear?
The head/bottom-of-page inconsistency can be fixed by running your binding when the DOM is ready, like this:
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
// code omitted for brevity
});
});
</script>

Categories

Resources