-1

I am new to JavaScript and JQuery and I am going through the tutorials.

I just want to ask, what is the equivalent of the following in JavaScript:

$(document).ready(function(){
    $("p").click(function(){
        $(this).hide();
    });
}); 

I am asking this question because I want to appreciate why they say JQuery makes things easier. Thanks in advance!

Munashe Tsododo
  • 197
  • 1
  • 2
  • 12
  • If nothing else the raw JS code is about 2-3 times the length (and less intuitive as to what it is doing). :) Note: You can also shorten your existing *DOM ready handler* to `$(function(){ your code here });` – Gone Coding Mar 30 '15 at 09:24
  • possible duplicate [$(document).ready equivalent without jQuery](http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery) – Kyojimaru Mar 30 '15 at 09:25
  • Okay @TrueBlueAussie Are you able to give me an idea of the code? Or point me to a link where I can view? – Munashe Tsododo Mar 30 '15 at 09:25
  • `Danbopes` has already provide links to the relevant parts. Note: jQuerys DOM ready handler does a lot more than just wait for the page load, so you get all sorts of features for free (e.g. cross-browser fixes). – Gone Coding Mar 30 '15 at 09:27

4 Answers4

1

This can tell you how to do $(document).ready() without jquery.

This can tell you how to do $('p') and this can tell you how to attach the click event.

This is the equivlant of $(this).hide() or $(this).show().

Suffice it to say, jquery is going to do a lot of the work to make sure that your code is browser compliant. This saves a lot of work trying to make it compatible for each and every browser.

Community
  • 1
  • 1
1

Well, basically, you could do the same thing with this js code (Note, that the DOMContentLoaded event does not get supported by all browsers):

document.addEventListener("DOMContentLoaded", function(event){
    var ps = document.getElementsByTagName("p");
    for(var key in ps){
        ps[key].onclick = function(){
            this.style.display = "none";
        }
    }
});

But jQuery is doing much more than that (therefore the DOMContentLoaded event is not an exact equivalent for $(document).ready). It checks for compatibility issues for example. Only the code behind $(document).ready() looks like this: (source here)

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            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", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == window.top ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}
Community
  • 1
  • 1
Markai
  • 2,058
  • 1
  • 8
  • 15
  • @FrancescoE. Yes, that is true. I edited the answer to clear out why I used window.onload there. Of course it is not the same, that is why I added the code for $(document).ready to show the difference – Markai Mar 30 '15 at 09:56
  • ok, but you don't obtain the same result. The `onload` contains the `document.ready`, but the first one is slower and is not the javascript equivalent, for me your answer is not correct – Francesco Mar 30 '15 at 09:59
  • @FrancescoE. point taken! I changed it to use the DOMContentLoaded event. But it should be pointed out, that this isn't an exact equivalent to $(document).ready – Markai Mar 30 '15 at 10:02
0

This is for your basic interactions with "p" document.getElementsByTagName('p')[0].addEventListener("click",function() { this.style.display = "none"; });

about "document ready function" it is much more complicated than it seems

Vitaliy Terziev
  • 5,298
  • 3
  • 15
  • 24
  • Your code is not exactly the same as `$("p").click(....` because `document.getElementsByTagName('p')[0].add...` only affects the first p element, while the jQuery code effects all of them. – Markai Mar 30 '15 at 09:42
  • yep, this is the case, but i think he/she need to find that for him/her self, i think it is pretty lazy to ask such a question on SO and to not search for it a couple of hours/days on google – Vitaliy Terziev Mar 30 '15 at 09:45
  • But giving incorrect answers to someone who tries to understand something isn't lame? – Markai Mar 30 '15 at 09:47
  • @Markai it is not incorrect actually i think it will be good when one finds that "0" - goes for element 1 and so on.. basic things and so important at the sam time, – Vitaliy Terziev Mar 30 '15 at 09:49
  • they are basic and that's why you shouldn't just post an answer where you do it wrong, because how should the op know, that jQuery doesn't just pick the first element that fits the selector? You just assume he knows exactly how jQuery selectors function but the question makes that pretty unlikely. Giving an incorrect answer because "he should figure it out himself" is pretty poor. You could just leave it then anyway – Markai Mar 30 '15 at 09:52
  • 1
    @Markai your example is overkill for complete beginer :) and does not show how things work under the hood ;) – Vitaliy Terziev Mar 30 '15 at 09:53
0

You are asking jQuery to execute the code inside the $(document).ready(function(){.....} when the DOM is fully read.

In javascript you obtain the same result with the following event:

 document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
  });

You don't actually need that if you place you script just before the </body> tag, in this way you are doing exactly the same!

The previous javaScript code and the $(document).ready(function(){.....} are different from the window.load event that occurs later, when all content (full css, images) also has been loaded.

Francesco
  • 1,313
  • 7
  • 14