How can I fire jQuery outside document.ready block? - javascript

The common method of starting jQuery is putting it in
$(document).ready(function() {
// put all jQuery stuff here
});
But what if I have a complicated site which uses basic jQuery in <head> and some custom functions that depend on the page type (e.g. if I have login page, fire some login ajax stuff).
So, how can I attach code to $(document).ready() or fire it later? Which JS syntax should I use?
Thanks for help!
My page structire is similar to this:
Display static header using PHP's include()
Add content inside <body></body>
Display the template footer
<?php
include_once('system/classes/class.display.php');
$d = new IFDisplay();
$d->display_header(array('subtitle' => 'Log In')); <-- Here it displays static
head tags. There is
document.ready in there.
I can't change it.
?>
<script type="text/javascript">
AND WHAT DO I NEED TO PUT HERE
</script>
<div>...</div>
<?php
$d->display_footer();
?>

If you aren't worried about race conditions, you should be able to use this:
$(function(){
//put your code here
});
As many times as you like.

If you have a block of code that you want to be able to run BOTH in a $(document).ready() function and sometime later like when an ajax call completes, then you can just define a function and call it both places like this:
// define this in the global scope or some other publicly available scope (not inside a document.ready() call).
function myOperation() {
// put your code here
}
$(document.ready(function() {
myOperation();
});
And, then sometime later (like in an ajax call in your other code), you can call that same function with this:
myOperation()

Related

Calling JS function from PHP not working

Using a method recommended by a user in a previous question I used just one document (index.php) to show different contents instead of creating one file for each one.
This is the code:
HTML
Home
More info
Contact Us
<div id="index">...index content...</div>
<div id="more_info">...more info content...</div>
JS
$(document).ready(function(){
function more_info(){
$('#index').hide();
$('#more_info').show();
}
});
PHP
<?php
if (isset($_GET['id_page'])) {
$id = $_GET['id_page'];
if ($id == 1) {
?>
<script>
more_info();
</script>
<?php
}
}
?>
That's not working. But if I change <script> more_info(); </script> for:
<script>
$(document).ready(function(){
$('#index').hide();
$('#quienes-somos').show();
});
</script>
It works. Why is this?
It looks like the problem you are having is because you are defining your more_info function inside of a function. This takes it out of the global scope which will not make that function accessible anywhere except for inside of your document ready function.
//more_info is now available globally
function more_info(){
$('#index').hide();
$('#more_info').show();
}
$(document).ready(function(){
//document ready code here
});
This should make the more_info execute when you output the JS function from PHP. Also it is good to note that since you are not executing the function on ready you will need to make sure the html is available for the JS to modify it. It is normally best practice to put all your JS just before the closing tag. This will ensure your html loads as quickly as possible and your JS will always have access to the HTML you are attempting to edit. With the JS in the head tag you need to make sure your JS is being called at the correct time using:
$(function() {
});
OR
$(document).ready(function() {
});
OR
$(window).load(function() {
});
All of these methods execute at different times during page initialization. With JS in the head tag your browser will need to download all the JS to the client before it can begin to render the HTML which will also add to time between going to the site and actually seeing the site.

Which event I have to use in jquery to get called before my page elements load?

I want to use boomrang framework in Jquery to get the bandwidth of the user's network which has to be displayed on the screen as "connection : fair/poor/good".
With on ready,on load, etc.., javascript function will be called only after the elements are ready to be accessed. But, I want the boomrang call to be called quite before that. Please tell me which event I have to use so that function call can happen before the elements of the page loads. Thanks in advance.<>
Note: I have tried by putting script tag at the top of the head tag. But still page elements are getting evaluated first (along with their el expressions).
If you want your function to be called before DOM creation then you dont need to call your function in any onload or on(document).ready, what you have to do is just call your function inside the script tag
For example (Script on the top of the page)
<script>
function abc()
{
// function desc
}
abc(); //Will be called as soon as the url is opened
$(document).ready(function()
{
abc(); // will be called when the DOM is ready
});
</script>
Use bw plugin from boomrang freamework
http://yahoo.github.io/boomerang/doc/howtos/howto-3.html

Can't call javascript from ajax div

I have some content loaded in my page using ajax. I want to run a JS function when some anchors are clicked. These anchors belongs to the code loaded using ajax. Both the ajax request and the JS function are located in a separate JS file, inside a jQuery(document).ready(function() {.
I have a few dozens functions in this JS file, and they're running fine, but this specific function is the only one called by code retrieved using ajax, and it is not working. My code:
html main file:
<!-- code -->
<div id="ajaxContentGoesHere">
<!-- content inserted here by ajax function -->
<td>Editar</td>
</div>
<script src="/js/myJS.js"></script>
</body>
/js/myJS.js file:
jQuery(document).ready(function() {
/*some other functions here*/
$("[id^='aLancamentoEdit']").click(function(){
console.log(1);
}
});
I tried to put the $("[id^='aLancamentoEdit']").click(function(){ inside the html main file, in a tag after the /js/myJS.js call. Didn't work.
Also tried to change the selector to match my anchor class (I declared a class for this). No success either. Finally tried also to put a name in the function and call it on onclick="" inside the anchor. Failed again.
What am I doing wrong?
Since the element by id starting with 'aLancamentoEdit' is dynamically added by ajax, you need to bind click handler to parent:
$('#ajaxContentGoesHere').on('click', "[id^='aLancamentoEdit']", function() {
console.log(1);
});
Use .on() for dynamic element events (ajax content in your case). Try:
jQuery(document).ready(function() {
/*some other functions here*/
$("#ajaxContentGoesHere").on("click","[id^='aLancamentoEdit']",function(){
console.log(1);
}
});

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

jQuery not working in external JavaScript

I am new to jQuery and am stuck at some strange issue. I am using jQuery's change and click methods. They are working fine when used in my HTML file in the <script> tag.
Like:
<script>
$("select,input").change(function ()
{
// My code and some alerts
});
</script>
When I copied the same in external JavaScript code without <script> and imported that in my HTML it was not at all working.
Are there any changes which are needed to use jQuery in external JavaScript code?
PS: Some other non-jQuery functions present in same external JavaScript code are successfully called from HTML.
First off, you don't want a <script> tag in an external JavaScript file, if that's how I'm reading your post.
The trick with jQuery is that your code is set to execute immediately.
You want to wrap your script so that it loads when the document is ready, in something like:
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
});
And you want to make sure that your file is loaded after jQuery (otherwise the $ global will not be set).
Additions:
Here is what your HTML should look like:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jscript/myExternalJs.js"></script>
Here is what your JavaScript code should look like (note there is no script tag inside the JavaScript file):
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
// Other event handlers.
});
As far as your other script... it sort of depends on what you're doing. The most important thing is to not try to hook event listeners up to objects that don't yet exist, which is why we use document.ready.
Did you make sure jquery is defined before your own jquery code?
You should also make sure the DOM is ready when dealing with jquery:
$(document).ready(function() {
$("select,input").change(function() {
// my code and some alerts
});
// more code here if needed, etc.
});

Categories