Is there anyway I could put this javascript code in the header tag?

I have a little div in my form that I need to hide ie onLoad first. the problem is when I put this in the <head> tag that it will try to execute, first throwing an error that is null, and when I include it under the form, it works fine. eg

this code works fine if the JS code is placed below.

 <div class="error" id="name_error"><p>Input Name</p></div> <input type="text" id="name" name="name" class="input-text" value="Enter Name..."/> <script type="text/javascript"> document.getElementById('name_error').style.display = 'none'; </script> 

and when I try to post the JS code above it doesn't work.

anyway, could I put the JavaScript code in the main tag, and should it hide the div when the page loads?

+4
source share
6 answers

In any case, can I put the JavaScript code in the main tag and it should hide the div when the page loads?

You need to wrap your code in an onload event:

 window.onload = function(){ document.getElementById('name_error').style.display = 'none'; }; 

This way you will not get an undefined error because the onload event is onload when the DOM is available along with other page resources.

+1
source

Sure. Just put it in the load event, for example:

 window.addEventListener("load", function() { document.getElementById('name_error').style.display = 'none'; }, false); 
+1
source

You might want to use jQuery . This is how it would be written.

 $(function(){ $('#name_error').hide(); }); 

Everything inside $(function(){ }); will be executed after loading the DOM, similar to window.onload , only with cross-browser support.

$('#name_error') is like a shortcut to document.getElementById('name_error') only using CSS selector syntax.

.hide(); is a shortcut to set style.display to 'none' .

EDIT: loading a window without jQuery.

After I posted this answer, I remembered Dustin Diaz 's post about the smallest DOMReady code. With his code, it will look as follows.

 function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()} r(function(){ document.getElementById('name_error').style.display = 'none'; }); 

More on line 1 at http://www.dustindiaz.com/smallest-domready-ever/

+1
source

Am I missing something? Why not just make the initial style "display: none"? Instead of leaving it by default and hiding it right away.

+1
source

Setting the display to none in the window.load event may cause the content to be initially visible - provided that the flash disappears. However, as indicated, you cannot change the display of the DOM element before rendering it.

A good approach is to add (or remove) the class in the html element using Javascript (which you can do in your head) and set a CSS rule that hides your element if the html tag has a set of classes.

see How to determine if the JavaScript browser is disabled and display a notification for an example.

+1
source

There were quite a few answers with different methods to delay the execution of the script, with some inconsistencies in the comments, so I wrote a little DEMO to compare what the real differences of all these approaches are, because they are certainly not equivalent.

For impatient people who do not want to see a demo, here are the most important things to keep in mind choosing the right tool for the job:

window.onload = function () {...};

  • it works in all browsers
  • deletes all previous handlers
  • it only starts after loading all images.

window.addEventListener ("load", function () {...});

  • it does not work in internet explorer
  • it only starts after loading all images.

jQuery (document) .ready (function () {...});

  • it works in all browsers
  • it starts as soon as the DOM is ready

Just for the curious, this is exactly what jQuery does to make sure your handlers are running as soon as the DOM is ready and running in browsers:

 // Handle when the DOM is ready ready: function( wait ) { // A third-party is pushing the ready event forwards if ( wait === true ) { jQuery.readyWait--; } // Make sure that the DOM is not already loaded if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, 

I show as an example that something that seems simple as a document handler can be quite complicated if you need it to work in all browsers and not freeze your scripts if some image or advertisement loads with a delay .

+1
source

Source: https://habr.com/ru/post/1341761/


All Articles