weird jQuery JSON function... whats going on here? - javascript

Im browsing the flot examples here http://people.iola.dk/olau/flot/examples/turning-series.html
(view source once there)
I came across this :
<script id="source" language="javascript" type="text/javascript">
$(function () {
var datasets = {
"usa": {...
The $(function() part. I get that its an anonymous function, I dont get why it is used here. Wouldnt this be just as good :
<script id="source" language="javascript" type="text/javascript">
var datasets = {
"usa": {...
I checked over at the jQuery docs (http://api.jquery.com/) and found no special use for function()

$(function () {
Is for executing the code when the DOM is ready, it's a document.ready handler in jQuery, the same effect as:
$(document).ready(function () {
You want to run certain things on document.ready so that the elements are there, for example if you're using $(".class") as a selector, you wouldn't want that code to run until the DOM was fully loaded, so the elements you're looking for are there, ready to be found by the selector...this means your code would always work, even if it's in the <head>.
For documentation, look at jQuery(callback) in the API.

This is shorthand for $(document).ready(handler) which waits until the DOM is fully loaded before running the anonymous function.

In jQuery, $(function() { is shorthand for $(document).ready(function() {.
Yes, your 2nd part would work equally well, but the first one guarantees that the entire DOM for the page is loaded before it is executed.

Related

How to call jQuery function in HTML <body> onload?

I want to call a jQuery function from an HTML <body> tag. Here's my HTML:
< body bgcolor="#ffffff" onLoad="???" >
How would I call a jQuery function when the page is loaded? My jQuery function looks like this
jQuery(function($){
var input_id;
//code
});
whatever code you write in the below method(block) would be executed automatically after the DOM load. You need not call this from HTML component again.
$(document).ready(function() {
//your code
});
This topic has been covered here before.
You are most likely looking for
$(document).ready(function() {
var input_id;
//code
})
Or
$(window).load(function($) {
var input_id;
//code
});
If you are curious about the difference between these two, see the JQuery documentation on the topic.
Also note that <body onload="">, which you seem to be trying to use, is generally not compatible with the above JQuery.
$(function() {
// code
});
This is shorthand for document.ready() so it will wait for the body to finish loading before executing.
HTML: You're on the right track, but you do not have to have put JS in the body tag. See the JS options below:
<body bgcolor="#ffffff">
JS
$(window).load(function($) {
functionA(arg1, arg2, arg3);
});
This will fire up functionA() once the DOM including graphics have fully loaded.
OR
$(document).ready(function($) {
functionA(arg1, arg2, arg3);
});
This will fire functionA() once the DOM has loaded and before any graphics finish loading.
As of Jquery 3, the following syntax is depreciated:
document.ready(function(){
//code
});
The recommended alternative in Jquery 3 is to use the following syntax (which in previous versions was just considered a shorthand syntax):
$(function(){
//code
});
Here is is the official Jquery explanation for why the first syntax was depreciated and is no longer recommended (https://api.jquery.com/ready/):
... The selection [of document] has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior.
document.ready(function($){
// here you go
})

Jquery to find and replace script line in header?

I have a script src for a deprecated version of JQuery which I cannot control (controlled externally via a CMS, not cross-domain, just no access to changing it) and I'd like to change the script src to a newer version of Jquery.
Old code:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
Replace with:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Once an external script has loaded, it can't be removed as it's already loaded into memory, so changing the source would just load another version of jQuery without removing the first version, so you'd have two versions of jQuery, creating a conflict, and in many cases nothing will work.
There is a workaround if you absolutely have to:
$(function() {
$j_142 = $.noConflict(true);
$j_142.getScript('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', function() {
$j_191 = $.noConflict(true);
});
});
FIDDLE
now you have two versions of jQuery mapped, and to use them you'd do:
$j_191('#selector')
of course, this would cause issues with code already written, but you could probably get away with just mapping the second script to a new variable or something ?
EDIT:
You could use a closure to map one of those values back to the dollarsign within the closure:
(function($) { //anonymous self invoking function
// now you could use the dollarsign as normal
$(function() { // document ready function
});
})($j_191);
You can use
var oldJquery = document.querySelectorAll('script[src="js/jquery-1.4.2.min.js"]');
oldJquery.src = "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
Once you do this, it will automotically will download coz it is live dom element. All changes should be reflected immediately.
But I would suggest that long term this is not good idea. what if CDN from google is down.
You might be in trouble. Just take precaution while doing this changes.
That easy, this is your code:
$("script[src='js/jquery-1.4.2.min.js']").attr('src', '//ajax.googleapis.com/ajax/libs/jquery/1.9.2/jquery.min.js');
This is example http://jsfiddle.net/rebeen/KwLM3/

jQuery not loading at all

I'm trying out jQuery for the first time, and I'm not sure how to make it work properly. I've included the following code near my opening <head> tag:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
Followed by the following jQuery code:
<script>
$('.darkmask > img').hover(function(){
$(this).parent().toggleClass('darkmask-hover');
})​
</script>
Unfortunately, this code doesn't work when I try it in a browser, or in JSFiddle. However, when I set JSFiddle's framework to load jQuery itself, rather than loading jQuery through my own code, the animation works properly.
Am I loading jQuery wrong? If so, what's the right way?
PRoblem is, your code in JSFiddle is executed on the loading on the page. In your code instead, the execution happens when the HTML elements are not yet loaded because it's in the HEAD, so the selectors like .darkmask actually refer to... nothing.
The solution is to use:
$(document).ready(
function()
{
... your code here
}
To ensure that it is executed when the page is loaded and ready, all the HTML elements are there and therefore JQuery selectors can operate on something.
Are there any HTML elements when the code is executed?
Try:
$(function () { // this function executes when the page loads
alert(x);
// put your code here
});
Wrap your entire code in the following:
$(document).ready(function() {
//ALL CODE GOES HERE
});
Wrap your code in:
$(function() {
.... Your code here ...
});
It will mean your code is executed after the DOM tree is loaded.
You do need to wrap your jQuery code within the ready function, like this:
$(document).ready(function(){
// put your code here.
});
Also make sure your script tags have type="text/javascript" as an attribute otherwise it won't get run as javascript.

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.
});

Dom loads two times

I have a very weird problem. I am using jQuery and i am using the $(function () to load functions when the dom is loaded. But with a unknown reason the code in the $(function () will run a second time. A preview is at: http://development.devhouse.nl/news/3/het-nieuwste-nieuwsbericht you will get 2 alert prompts, but there is only 1 written in a $(function () . The exact code is:
<script type="text/javascript">
$(function () {
alert('Test');
});
</script>
And the whole source can be found here(open the source in your browser): http://development.devhouse.nl/news/3/het-nieuwste-nieuwsbericht
Please help me. I am hopeless....
Tom
I suppose because the script is in your html body instead of in the head. Move it to the head, and it only fires once.
Is there a reason you have it there?
EDIT: For clarification, as Marcel Korpel noted, scripts can be nested in the body, and there can be performance reasons to have them at the end. But in this situation, the script was nested inside an element within the body. This works, but can lead to unexpected behavior if that element is manipulated in certain ways.
$().ready(function(){
alert('Test');
});

Categories