javascript error while loading the document - javascript

Im trying to run the below script to understand the Javascript object and inheritance but don't see anything being displayed.
<html>
<head>
<script>
$(document).ready(
function Person(){
alert('New Person Created');
}
Person.prototype.sayHello = new function(){
alert('Hello');
};
var x = new Person();
x.sayHello();
var newfunction = x.sayHello;
newfunction.call(Person);
);
</script>
</head>
<body>
</body>
</html>

$ is defined in jQuery, you need to include jQuery library before using the $
you can include jquery library using cdn like this,
<script src ="//code.jquery.com/jquery-1.10.2.min.js"></script>

The first line of your script is jQuery. If you want to use jQuery you should include it first (based on what you have written I strongly suspect you don't need or want it just yet).
Alternatively, just drop the $(document).ready part and its {}s and that should get you going.
Also, take a look at your developer tools menu and get your JavaScript console open. It will have told you about this error.

When you use a construct like $(document), you are calling a function $, which is defined as jQuery. You need a <script> tag in your document to load the correct version of jQuery. Also, check your browser console. You will see an error there about $

The only thing I can see wrong is that you are trying to use the jQuery library, but you've never actually included it.

Related

Be sure that never have JQuery conflict

I need to create code which can be used as snipped for every site.
When I copy paste this code to any html in the world this should work:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript"> my_jQuery = $.noConflict(true);</script>
<script type="text/jscript">
my_jQuery(document).ready(function () {
my_jQuery("#myDiv").html("Hello world");
});
</script>
<div id="myDiv">
</div>
Of Course in real world logic will be more complex but principle is same.
So this must work even if site already have JQuery, if have same version of JQuery,if have different version of JQuery, or even if does not have JQuery at all.
I want be sure that client does not use some old version of JQuery, so I want always use my JQuery.
What do you think, will this work or there is something that I have not consider?
I think that this question should be faced in an architectural way, knowing what libraries/frameworks are available is a design concern... Basically, you shouldn't need to check dependencies at runtime... if you write jQuery, you must be sure that jQuery exists!
By the way, there are some cases where you can't do it, for example, if you are writing a public/api (a snippet that runs in heterogeneous environments). In these cases, you can do:
mark jQuery as peer-dependencies
Check at runtime.
There is an example of runtime checking:
<script>
(function($) {
var jQueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js';
$ || (document.writeln('<script src="'+ jQueryUrl +'"></script>'));
})(window.jQuery);
</script>
In order to avoid conflicts, finally, you don't need to use jQuery.noConflict, you need to work with javascript scopes (closures)... basically, never try to access the global jQuery alias $ (never use global vars), simple pass it as function param:
(function($) { console.log('$', $); })(window.jQuery)
window.jQuery(document).ready(function($) { console.log('$', $); });
The first thing we need to do is check if jQuery is present on the website. jQuery is the global variable so it should be in window object if it is loaded. We can check it like this: if (window.jQuery) {}
If the jQuery not present we can dynamically load it adding script tag with desired jQuery version. So the snippet answering for checking if jQuery is loaded and loading if it's not would be like:
if (!window.jQuery) {
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.src = 'http://code.jquery.com/jquery-1.12.1.min.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
That would work for
So this must work even if site already have JQuery,
if have same version of JQuery,
if have different version of JQuery,
or even if does not have JQuery at all.
As you can see as per your code, that would work fine for all three situations but 4th one. For this case you have to have a check to find if window has jQuery object. That can be done with:
if(window.jQuery){
var my_jQuery = $.noConflict(true);
my_jQuery(document).ready(function () {
my_jQuery("#myDiv").html("Hello world");
});
}
Note:
<script type="text/jscript">
would not work in the browsers other than IE.

"TypeError: $ is not a function" after loading some scripts into wordpress

We start to provide a HTML-Snippet like Google or Facebook does for its advertising things or the integration for the Facebook like button. It contains a business application.
Our HTML-Snippet loads a script and contains a few more informations:
<div id="ncc" data-hash="" ng-jq>
<div id="wiz" ng-controller="WizardCtrl"></div>
<script src="{{URLTOSCRIPT}}/load.js"></script>
</div>
The script checks if a jQuery is installed and loads all related things into the DOM and at the ends inits an angular-Application.
All this works fine on pages that havn't enabled jQuery.noConflicts-Mode.
After the latest Wordpress-Updates we got an ERROR
"TypeError: $ is not a function"
We tried to get rid of it using some workaroungs like
jQuery(document).ready(function($){
$(function () {
//code to execute
});
OR
jQuery(document).ready(function(){
var j = jQuery.noConflicts();
j(function () {
//code to execute
});
and changed also all references in the angular-part. But nothing working really well.
Any suggestions?
We are using AngularJs v1.4.7, jQuery v1.11.3 (started to migrate to 2.1.4), the
Sometimes when more versions of jQuery are loaded or if it conflicts with another library you can get that error:
have you tried to replace in all of your code the $ symbol with the word "jQuery"?
So your example would become:
jQuery(document).ready(function(){
jQuery(function () {
//code to execute
});
Note: I don't think that in this case passing "$" as a parameter is needed anymore ;)
EDIT: there is also another possibility:
you say that you're using the $ sign (i guess to avoid the usual conflicts in wordpress) in this way:
jQuery(document).ready(function($){
$(function () {
//code to execute
});
But this will make the $ symbol available only inside the ready() function.
Did you check if you have somewhere code using the $ where you actually aren't allowed to (or in other words if you have any piece of your js code where $ isn't mapped as "jQuery")?
EDIT 2: The only working solution in the end was:
(function($,undefined){
$(document).ready(function(){
//code to execute
});
})(jQuery);"
Make sure jQuery is loaded before any other script that uses certain jQuery functions.
Normally those errors arise, when the jQuery library wasn't loaded yet. Make sure that a $()-call is called after jquery was loaded, which normally happens at the end of your file to speed up loading times.
Therefore putting
<script src="{{URLTOSCRIPT}}/load.js"></script>
to the end of the body-tag should help.
Usually when you get this error: "TypeError: $ is not a function"
it means, you a missing a JQuery library or they are not placed in the correct order. Ordering JQuery libraries is important.
$ is not a function. It means that there is a function named $, but it does not have a plugin/widget named selectable. So, something has stolen your $ or there is another library added after it, or it was never loaded.
Your script file is not loading properly or script file is not available.
open browser inspect element and put this code
jQuery().jquery.
it's display which jquery version is use.
this is for testing
jQuery(document).ready(function()
{
alert("test");
});

Why does jQuery's ajax automatically run scripts?

I noticed recently that if jQuery ajax is called right after injecting jQuery into an inner iframe, jQuery loses its functions - like jQuery(..).dialog(), .draggable, and any other plugins. If the ajax call is commented out, the jQuery works fine. Is this a known bug, or something I'm doing wrong? This problem can be seen in this file, with jQuery in the same directory:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="jquery.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
Try and <button id="btn">load</button>
<iframe width=300 height=300></iframe>
<script>
"use strict";
jQuery('#btn').click(function(){
var $ = jQuery;
console.log(typeof jQuery('iframe').dialog);
var doc = jQuery('iframe')[0].contentDocument;
function insertscript(src) {
var newscript = doc.createElement('script');
newscript.setAttribute('src',src);
doc.documentElement.appendChild(newscript);
}
insertscript('jquery.js');
//This breaks the jQuery plugins:
var test = $.get('jquery.js',function(){
//Now we know jQuery should be in the frame.
});
//So does this:
//jQuery.ajax({url:'http://192.168.1.17/wordpress/wp-includes/js/jquery/jquery.js',cache:true,processData:false});
console.log(typeof jQuery('iframe').dialog);
window.setTimeout(function(){
//jQuery is no longer the original jQuery object. Note the cached reference $().dialog does exist though.
console.log('after awhile... dialog is ' + typeof jQuery('iframe').dialog);
},3000)
//jQuery.ajax({url:jqurl,cache:true,processData:false});
});
</script>
</body></html>
This is a minimal sample of the problem, making sure the iframe has loaded a certain jQuery.js (then ajax should have the cached script) before some other stuff is added to the iframe.
Click load, and after while, console log will show "after awhile... dialog is undefined" - only when ajax was used.
Update: It looks like $.get('jquery.js') actually runs the script. $.get('alert.js') shows an alert, when alert.js has an alert function. (In the case of jQuery, re-defining the global jQuery reference.) Why does jQuery's ajax have this behavior? Does this happen with all ajax implementations?
As someone answered earlier (whose answer got deleted?), jQuery ajax automatically chooses what to do depending on what type of content you requested. (An unfortunately under-documented feature). loading an external js will not just return when the browser has fetched the script, it will also run the script.
Whenever you re-include jQuery at a later point, it rewrites the window.jQuery object, therefore removing the jQuery.prototype.dialog, etc.
The Firefox .watch function can be helpful in cases like this, to see where something got redefined. This, for example, would give you a stack trace of anything that redefines jQuery:
window.watch('jQuery',function() { console.trace() } )

$ is not a function

<script type="text/javascript" src="framework/resources/jquery-1.5.1.js"></script>
<script type="text/javascript">
var blink = function() {
$('#blink').toggle();
};
</script>
Throws an error saying
$ is not a function
When using an external JavaScript file which gets referred after jQuery I can only seem to use jQuery within the ready function. Is there something I should know about using jQuery in this manner?
That error means jquery isn't loaded
jQuery may be conflicting with another definition, the fact that you can use it in the ready function seems to indicate that it is at least loaded. Have you tried using:
<script type="text/javascript" src="framework/resources/jquery-1.5.1.js"></script>
<script type="text/javascript">
var blink = function() {
jQuery('#blink').toggle();
};
</script>
Sometimes it is cleaner to go direct to the object. If you find that resolves your problem you may wish to switch to noConflict mode which is described in more detail in the docs here:
http://api.jquery.com/jQuery.noConflict/
Hope that helps.
Have you referenced jQuery as the first script in your page? Does the path exist? Try using Google's, just to test:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
It seems that jQuery is conflicting with any existing javascript library.
I hope this link might help.

Can I reset the name of jQuery's global object?

Let me give my question some context. I have a JavaScript widget. The widget includes a copy of jQuery from my site. This widget is placed on a third-party site. The widget parses a JSON feed and injects the contents into the DOM. Pretty simple stuff.
If the third-party page already has jQuery referenced and relies on jQuery plugins, conflicts could arise. Especially, when the third-party site references a different version of jQuery. $.noConflict() is useful, but the existence of plugins make it unreliable. From the $.noConflict() documentation:
If necessary, we can free up the
jQuery name as well by passing true as
an argument to the method. This is
rarely necessary, and if we must do
this (for example, if we need to use
multiple versions of the jQuery
library on the same page), we need to
consider that most plug-ins rely on
the presence of the jQuery variable
and may not operate correctly in this
situation.
To get around this issue, my idea is to reset the name of the jQuery global object. At the bottom of the jQuery source, there are these lines:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
Could I refactor the lines to:
// Expose jQuery to the global object
window.myjQuery = jQuery;
I've removed the shorthand $ variable, and I've changed jQuery to myjQuery. Now my code can look like this:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>myjQuery</title>
<script type="text/javascript" src="myjquery-1.4.js" />
<script type="text/javascript">
// .ready() can alias the jQuery object
// I can pass $ and write code as normal
myjQuery(document).ready(function($) {
$('p').css('color', 'red');
});
// Fails
jQuery(document).ready(function($) {
$('p').css('color', 'blue');
})
// Fails
$(document).ready(function() {
$('p').css('color', 'green');
})
</script>
</head>
<body>
<p>myjQuery changed my color to red.</p>
</body>
</html>
Is this a good idea? I don't know the internals of the library enough to say for sure. I understand the library is basically a closure, so I'm guessing this approach is OK. Thoughts?
EDIT: I've accepted Doug's answer because he provided code which is almost identical to an example on the $.noConflict() documentation page. I didn't notice it before. Here is the example:
// Completely move jQuery to a new namespace in another object.
var dom = {};
dom.query = jQuery.noConflict(true);
// Do something with the new jQuery
dom.query("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
// Do something with another version of jQuery
jQuery("div > p").hide();
It's not normally a good idea to edit a released file if you don't need to. I read your question, and this solution will work for your needs. Don't edit the jQuery core at all. Do this:
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript">
// Revert $ and jQuery to their original values:
window.myjQuery = jQuery.noConflict(true);
(function($){
// Inside here, $ = myjQuery
$(document).ready(function(){
});
})(window.myjQuery);
</script>
The important thing is for your widget to include jQuery, then immediately call noConflict(true) and store it in a variable.
If you follow these steps exactly, it will not affect existing jQuery instances or plugins on the page. It will only give you a private version of jQuery in the variable myjQuery for your own plugin.
Secondly, using a self executing anonymous function, you can create a private scope for your widget where $ equals your included jQuery file.

Categories