简体   繁体   中英

is there anyway i could put this javascript code in head tag?

i have few div's in my form which needs to be hidden at first ie onLoad. the problem is when i put that into <head> tag it will try and execute first giving out the error that div has value null, and when i include it below the form it works perfectly. for example

this code works fine given 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 placing the JS code above it doesn't work.

is there anyway i could place the JavaScript code in head tag and it should hide the div when the page loads?

is there anyway i could place the JavaScript code in head tag and it should hide the div when the page loads?

You need to wrap your code in onload event:

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

This way you won't get undefined error because the onload event is triggered when DOM is available along with other page resources.

Sure. Just put it into a load event, like this:

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

You might want to consider using jQuery . Here is how it would be written.

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

Everything inside $(function(){ }); will execute after the DOM is loaded, 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 for setting the style.display to 'none' .

EDIT : non-jQuery window load.

After I posted this answer, I remembered a post by Dustin Diaz about the smallest DOMReady code. With his code, it would look like this.

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

Read more about line 1 at http://www.dustindiaz.com/smallest-domready-ever/

Am I missing something here? Why not just make the initial style 'display:none'? Rather than leaving it to the default and then immediately hiding it.

Setting the display to none on the window.load event can result in the content being initially visible - giving a flash as it disappears. However, as pointed out you can't change the display of a DOM element before its rendered.

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

see: How to detect if browser JavaScript is off and display a notice for an example.

There have been quite a few answers with different methods to delay the execution of the script, with some controversies in the comments, so I have written a little DEMO to compare what are the real differences of all of those approaches, because they are certainly not equivalent.

For the impatient who don't want to see the 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
  • it removes all previous handlers
  • it fires only after all images are loaded

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

  • it doesn't work in Internet Explorer
  • it fires only after all images are loaded

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

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

Just for the curious, this is what jQuery is actually doing to make sure that your handlers are fired as soon as the DOM is ready and to work across 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 it as an example that something that seems simple like a document ready handler may actually be quite complicated if you need it to work on all browsers and not hang your scripts if some image or advertisement is loading with a delay.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM