Trying to hide the document until it's updated with JavaScript - javascript

This is my ready handling:
$(document).ready(function() {
$(document).hide();
$('.foo').each(function(elem, i) {
$(elem).text('So long and thanks for all the fish');
});
$(document).show();
}};
What I'm trying to do is hiding the document completely until everything is ready on my terms, but it seems that the show() function doesn't wait for the elements iteration.
By the way, I tried changing show() and hide() to css('display', 'hide') and css('display', 'block') but still, you can the text is changing in your eyes.
How do you make sure all your code ran before calling show()?

Let's suppose you fix this by hiding the body or a container element. That won't do the trick, and here's why:
What happens during the time after the document is (mostly) loaded but before you hide the document?
That's right, the document may get displayed during that time despite your best efforts.
So what you could do instead is use a CSS class that hides, say, the body without any JavaScript intervention. For example:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
body.hide { display: none; }
</style>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready( function() {
$('.foo').each(function( i, elem ) {
$(elem).text( 'So long and thanks for all the fish' );
});
$('body').removeClass( 'hide' );
});
</script>
</head>
<body class="hide">
<div class="foo"></div>
</body>
</html>
Of course this does mean that if JavaScript is disabled, your document won't be visible at all. What if you want to have a non-JavaScript fallback? In that case you could do it like this instead. We'll hide the html element instead of the body because that way we know the code will work in the head (the body element may not exist yet at this point), and only hide it if JavaScript is enabled:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
html.hide { display: none; }
</style>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('html').addClass( 'hide' );
$(document).ready( function() {
$('.foo').each(function( i, elem ) {
$(elem).text( 'So long and thanks for all the fish' );
});
$('html').removeClass( 'hide' );
});
</script>
</head>
<body>
<div class="foo">
This content is displayed if JavaScript is disabled.
</div>
</body>
</html>
Now you have a non-JavaScript fallback, but the document will still be hidden immediately when JavaScript is enabled, because of the code that adds the hide class.
Also note that you had the parameters reversed in your $().each() callback. (Interestingly enough, the order you used makes much more sense and indeed is the order used by the newer native .forEach() function. The order in $().each() is really backwards - one of those things that seemed like a good idea at the time but really was just a mistake.)

You can not hide() the document. Instead, try hiding the main container element on your page; or hiding the body e.g. $('body').hide() might work as well.
Just an aside: the display property should be none. hide is not a valid value.

Related

document.getElementsByTagName returning undefined on placing the script after body

I know that this is a frequently asked question.
I have tried all the methods like using onload() for body tag,
placing the script after the DOM elements and using self invoking function.
Yet I get that my element is undefined.
P.S: document.getElementsByTagName('') replaced with document.getElementById('') works fine. Why is that? Please explain both of my doubts. Here is my simple code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
document.getElementsByTagName('p').setAttribute('draggable', true);
}
</script>
</body>
</html>
getElementsByTagName (as the name suggests) returns an array of elements. If you want the first one, take the first one.
.highlight{ color: red}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
var elem = document.getElementsByTagName('p')[0];
elem.setAttribute('draggable',true)
elem.classList.add('highlight');
}
</script>
</body>
</html>
As for why dragging is not working, perhaps the documentation might shed some light
By default, only text selections, images, and links can be dragged. For all others elements, the event ondragstart must be set for the drag and drop mechanism to work, as shown in this comprehensive example.
getElementsByTagName returns array of results, not just a single result like getElementById. Try to use getElementsByTagName('p')[0].

FadeinLeft Image scroll Waypoint

I have tried different websites even tried to decode waypoint guide but no luck. I can't seem to get scroll function to work with following code. (reference: http://blog.robamador.com/using-animate-css-jquery-waypoints/)
Any help will be greatly appreciated.
<!doctype html><html><head><link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.0/animate.min.css">
<style>
img {
margin:1000px 0;
display:block;
}
</style>
<script>
//Animate from top
$('.animated').waypoint(function() {
$(this).toggleClass($(this).data('animated'));
},
{ offset: 'bottom-in-view' });
//Animate from bottom
$('.animated').waypoint(function() {
$(this).toggleClass($(this).data('animated'));});
</script>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<img class="animated" data-animated="fadeInLeft" src="http://placekitten.com/g/200/300">
<img class="animated" data-animated="bounce" src="http://placekitten.com/g/200/300">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.4/waypoints.min.js"> </script>
</body>
</html>
First of all, put the jQuery script and Waypoint script inclusion in the HEAD tag. This is, in the 99% of the case, the right way to include javascript libraries in your DOM.
Second thing: you write your javascript code in the HEAD tag (it's right), but without a "start control". In your case, the browser start to execute your javascript code before reading the rest of the DOM, so it can't attach events on the right elements (the images with class "animated") because it haven't read them yet. In simply word, when the browser start to read your SCRIPT tag, it don't know who ".animated" are, so it do nothing.
There are two way to resolve your problem:
1 - Move you SCRIPT tag and its content at the end of the BODY tag.
2 - Wrap you javascript code in a DOM.ready state like:
<script>
$(document).ready(function() {
//Animate from top
$('.animated').waypoint(function() {
$(this).toggleClass($(this).data('animated'));
}, {
offset : 'bottom-in-view'
});
//Animate from bottom
$('.animated').waypoint(function() {
$(this).toggleClass($(this).data('animated'));
});
});
</script>
Honestly, I prefer the option number 2. =D

Define specific CSS-style only if JavaScript is enabled

My webpage contains a DIV. If Javascript is enabled, I want the DIV to be invisible (display: none;) when the page loads. If JS is disabled, I want it to be visible (display: block;).
I can do:
document.write('<div style="display:none;">...</div>');
or
document.getElementById('foo').style.display = 'none';
With the first code there won't be a DIV if JS is disabled. With the second, the DIV will be visible when the page loads and disappear when the JS is executed.
I'm too stupid to solve this.
Can I put JavaScript inside the <div>-tag to write only the style? Certainly not like this:
<div <script>document.write('style="display:none;"');</script>>
Maybe something like:
<div onLoad="document.write('<div style="display:none;">...</div>');">
Does someone have an idea?
One problem with displaying an element unless JS hides it is that, even with JS on, the element is likely to display until the JS kicks in. So it's often better to have some JS at the top of the file that adds a class to the root element straight away, to get in before the CSS loads. Here's a simple example (in my noob JS):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script>
(function() {
var root = document.querySelector('html');
root.className = "js";
}());
</script>
<style media="all">
div {width: 500px; height: 200px; background: blue;}
.js div {display: none;}
</style>
</head>
<body>
<div></div>
</body>
</html>
This is much better than using oldfashioned <noscript> and document.write() etc.
EDIT: I should just note that an easier way to target the html element is with document.documentElement. Thus, the code above could be written as—
<script>
(function() {
document.documentElement.className = "js";
}());
</script>
Why don't you just put the <div> in a <noscript>?
<noscript><div style="display:none;">...</div></noscript>
Now you don't even have to use Javascript to deal with it.

Hide everything on dom until everything is loaded

I am trying to change the content of a div on the page but the page has a lot of things to load and on slower computers there is a flicker where you can see the div changing (changing through jquery btw). Is there anyway that everything can be hidden and display it all at including the changes I made using jquery?
I had a similar issue with my web application.. This is what I did
Hide body in HTML
<body style="display:none">
And write this script :
$(window).bind("load", function() {
$("body").fadeIn(100);
});
OR this script
$(window).load(function () {
$("body").fadeIn(100);
}
This creates beautiful effect and shows the page ONLY after everything is fully loaded..
Perhaps you could do something like
<head>
<style>
body{
display:none;
}
</style>
</head>
<body>
flickery <div></div>s go here
</body>`
And your script
$(window).load(function(){
$(document.body).css("display","block"); //shows it when all the elements are ready for presentation
});

TypeError is Null?

This is an error in Firebug I keep seeing.
TypeError: $("#gallery-nav-button") is null
[Break On This Error]
$('#gallery-nav-button').addClass('animated fadeOutRightBig');
Here is my code:
JS
$(function() {
$("#close-gallery-nav-button").click(function() {
$('#gallery-nav-button').addClass('animated fadeOutRightBig');
});
});
HTML
<div id="gallery-nav-button">
<h4 id="close-gallery-nav-button">X</h4>
<h3 class="text-center small-text"><a class="inline text-center small-text" href="#gallery-nav-instruct">Click Here for Gallery <br /> Navigation Instructions.</a></h3>
</div>
CSS
#close-gallery-nav-button{
text-indent:-9999px;
width:20px;
height:20px;
position:absolute;
top:-20px;
background:url(/images/controls.png) no-repeat 0 0;
}
#close-gallery-nav-button{background-position:-50px 0px; right:0;}
#close-gallery-nav-button:hover{background-position:-50px -25px;}
I also want to add - because this is the #1 Google search result for the important error message "TypeError: [x] is null" - that the most common reason a JavaScript developer will get this is that they are trying to assign an event handler to a DOM element, but the DOM element hasn't been created yet.
Code is basically run from top to bottom. Most devs put their JavaScript in the head of their HTML file. The browser has received the HTML, CSS and JavaScript from the server; is "executing"/rendering the Web page; and is executing the JavaScript, but it hasn't gotten further down the HTML file to "execute"/render the HTML.
To handle this, you need to introduce a delay before your JavaScript is executed, like putting it inside a function that isn't called until the browser has "executed" all of the HTML and fires the event "DOM ready."
With raw JavaScript, use window.onload:
window.onload=function() {
/*your code here*
/*var date = document.getElementById("date");
/*alert(date);
}
With jQuery, use document ready:
$(document).ready(function() {
/*your code here*
/*var date = document.getElementById("date");
/*alert(date);
});
This way, your JavaScript won't run until the browser has built the DOM, the HTML element exists (not null :-) ) and your JavaScript can find it and attach an event handler to it.
I have several scripts running on this page and evidently one script was conflicting with another. To solve my issue I added jQuery.noConflict();
var $j = jQuery.noConflict();
$j(function() {
$j("#close-gallery-nav-button").click(function() {
$j('#gallery-nav-button').addClass('animated fadeOutRightBig');
});
});
As additional comment on #1 solution:
Another possibility for loading the script after finishing/building the HTML should be placing a defer parameter inside the script tag:
<script defer type="text/javascript" src="x.js"></script>
I agree with the advice given above, relating to the onload event. https://stackoverflow.com/a/18470043/2115934
A more simple solution (though not necessarily a better one) is to put your script tag just before the closing body tag of the document.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1></h1>
<p></p>
<script src="script.js" type="text/javascript"></script> <!-- PUT IT HERE -->
</body>
</html>
I know this has been answered and it is an old post but wanted to share my experience. I was having the hardest time getting my code to load and was getting this error constantly. I had my javascript external page loading in the head section. Once I moved it to just before the body ended the function fired up right away.

Categories

Resources