0

Does a click event always need to be placed inside (document).ready(function() as example below because I have seen click(function() located outside of it and I am wondering how to do it can be done

$(document).ready(function(){

    $('#checkout').click(function() {

        alert("Thanks for visiting!");
    });

});

6 Answers 6

1

It doesn't need to be in a $(document).ready();. It's the same as any javascript. It needs to be placed either after the elements it will be accessing, or in a $(document).ready();. If you put your script directly after the element you want add a click event to you can speed up your page: http://encosia.com/dont-let-jquerys-document-ready-slow-you-down/

Sign up to request clarification or add additional context in comments.

Comments

1

It doesn't have to be inside the ready function.

That just makes sure everything is loaded before the event is attached to the node.

Comments

0

The click function can be placed anywhere and have the same effect on the selection ($).

The selection function needs to be placed in such a way that it can select the nodes necessary. If the script tag comes before the content being selected in the DOM tree, you'll need to wait for the document to be ready or the window to have finished loading before the selection will succeed.

The following will work:

JS

$('#foo').click(...);

HTML

<div id="foo"></div>
<script src="location/script.js"></script>

But if you change the HTML around, this wont work:

<script src="location/script.js"></script>
<div id="foo"></div>

When the script is executed, the element with an id of foo doesn't exist yet. Which is why you typically wrap event handlers in the document ready event callback.

Comments

0

If you place #checkout BEFORE this jquery click event, you can let it without .ready()

http://sandbox.phpcode.eu/g/fb8e7.php

Comments

0

.click method binds handler for click event to some element. If it is inside the $.ready method, than binding will be executed after DOM is loaded. Else - binding will be executed immediately. As result - there is no difference. Your button (or something else) will work fine on click event

P.S. Problem may occur if you place .click method outside the $.ready and before your element (the target of event) is written

Comments

0

You may be able to use the jQuery live() event to broaden your possibilities of where you can put it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.