Understanding concept of plugin - $ / jQuery is not defined - javascript

I wrote one plugin with following syntax:
(function($){
$.fn.samplePlugin = function() {
return this.each(function() {
//My logic here
});
};
})(jQuery);
Then i called on load as
$(document).ready(function(){
$('#sample').samplePlugin();
});
Now i have these two errors in my console:
ReferenceError: jQuery is not defined
ReferenceError: $ is not defined
Can you please tell me what i'm missing and what should be the flow of usage of $ annotation when u create or include plugins?
Thanks,

Include jQuery before your plugin.

(1) Check if you have correctly included the jquery lib. in your code before calling your plugin.
(2) If you are on chrome to verify if jquery file is downloaded, open developer tools[shortcut F12 in windows] and switch to resources tab. See if jquery file is downloaded under scripts in your page resources.

write make sure jquery file is being loaded properly
If you are using jQuery UI library then please ensure that order is correct. You first need to include reference of jQuery library and after that jQuery UI library.

var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
jq.onload = procede;//make sure you don't type parenthesis
//i.e. 'procede()' runs function instantly
// 'procede' gives it a function to run when it's ready
...
function procede()
{
//jQuery commands are loaded (do your magic)
}

Have you included jQuery above your function?
If yes then use
$= jQuery.noConflict();
above calling your function.

Related

Use both $ and jquery as variable

In my project every page loads a cdn jquery script. some use $ and some use jquery. and now I have to use my new script file 'myNewScript.js' in every page.
If I write my function like $(function (){}) it gives error on some pages like
$ is not function
and if I write function like this jquery(function (){}) then it also give error on other page like
jquery is not a function.
I want to know can we use both $ and jquery as variable . like in same script file say 'myNewScript.js' I want to write $(function (){}) and jquery(function (){}).
Every thing is dependent on each other so I can't reverse the loading of the script. I can't think of any solution...
jQuery should always be available using the name jQuery (note the uppercase Q). So use that:
jQuery(function (){})
You can also wrap your code in an IIFE if you would like to refer to jQuery as $ while dealing with the uncertainty whether the global $ actually refers to it:
(function ($) {
$(function () {
// on ready stuff
});
})(jQuery);
Define jQuery locally for yourself by looking for both variables.
var myJquery = jquery || $;

Enqueueing Javascript and jQuery in a Wordpress plugin

I am a beginner to PHP and I'm trying and failing to get it to cooperate in loading a basic test alert in Javascript/jQuery. I'm creating a plugin for a Wordpress site and I just need to make sure that I can successfully run Javascript programs on the page before I can really start writing for it. Here is what I have so far:
The .js file is just a test alert, written with jQuery.
$(document).ready(function () {
alert("Your plugin's working");
});
The PHP file is an extremely simple plugin designed to run the alert.
<?php
/**
* Plugin Name: PanoramaJKM
* Plugin URI: unknown
* Description: Should alert on loading
* Version: 0.1
* Author: Matt Rosenthal
* Author URI: unknown
*/
function loadQuery() {
if (!is_admin()) {
wp_enqueue_script('jquery');
}
}
add_action('init', 'loadQuery');
function headsUp() {
wp_enqueue_script('alert-js', plugins_url('/js/alert.js', __FILE__), array('jquery'));
}
add_action('wp_enqueue_scripts', 'headsUp');
?>
Whenever I attempt to load the plugin on my Wordpress site, the JS console spits this error at me:
Uncaught TypeError: undefined is not a function
I can get the JS alert to show if I change my alert.js file to be without jQuery. However, I need jQuery to write the final plugin and I feel like I'm missing something that's easily fixable. Any help would be greatly appreciated! I've already tried following the advice of other SO posts and a couple of online guides with no success.
Dave Ross' answer is spot on. I'll add that, this is the most common format:
jQuery(document).ready(function($) // <-- $ as shortcut for jQuery
{
alert("Your plugin's working");
});
And you don't need add_action('init', 'loadQuery');. jQuery is already being loaded as a dependency for alert-js and the correct place to enqueue is the action hook wp_enqueue_scripts (which only runs on the frontend).
WordPress loads jQuery in noconflict mode because it ships with Prototype as well. So, you can't refer to jQuery with $, you need to spell out jQuery. Your Javascript code needs to be:
jQuery(document).ready(function () {
alert("Your plugin's working");
});
Alternately, you can wrap your code in a self-executiing anonymous function which defines $ inside of it:
(function($) {
$(document).ready(function () {
alert("Your plugin's working");
});
})(jQuery);
I believe there is an issue using $ in wordpress. Try using jQuery(document).ready(....

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

Hi I am having a "Uncaught ReferenceError: $ is not defined" while using bellow codes
I am currently getting the following error in my log. I have been looking at the samples in the framework and I just can't seem to find where the error is. It's been over a decade since I have done any HTML or js and what I did back then was very basic stuff. Any help would be appreciated
<script type="text/javascript">
var sQuery = '<?php echo $sQuery; ?>';
$(document).ready(function(){
if($('input[name=sPattern]').val() == sQuery) {
$('input[name=sPattern]').css('color', 'gray');
}
$('input[name=sPattern]').click(function(){
if($('input[name=sPattern]').val() == sQuery) {
$('input[name=sPattern]').val('');
$('input[name=sPattern]').css('color', '');
}
});
$('input[name=sPattern]').blur(function(){
if($('input[name=sPattern]').val() == '') {
$('input[name=sPattern]').val(sQuery);
$('input[name=sPattern]').css('color', 'gray');
}
});
$('input[name=sPattern]').keypress(function(){
$('input[name=sPattern]').css('background','');
})
});
function doSearch() {
if($('input[name=sPattern]').val() == sQuery){
return false;
}
if($('input[name=sPattern]').val().length < 3) {
$('input[name=sPattern]').css('background', '#FFC6C6');
return false;
}
return true;
}
</script>
It seems you don't import jquery. Those $ functions come with this non standard (but very useful) library.
Read the tutorial there : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
It starts with how to import the library.
No need to use jQuery.noConflict and all
Try this instead:
// Replace line no. 87 (guessing from your chrome console) to the following
jQuery(document).ready(function($){
// All your code using $
});
If you still get error at line 87, like Uncaught reference error: jQuery is not defined, then you need to include jQuery file before using it, for which you can check the above answers
Put this code in the <head></head> tags:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
If you are sure jQuery is included try replacing $ with jQuery and try again.
Something like
jQuery(document).ready(function(){..
Still if you are getting error, you haven't included jQuery.
I know this is an old question, and most people have replied with good answers. But for reference and hopefully saving somebody else's time. Check if your function:
$(document).ready(function(){}
is being called after you have loaded the JQuery library
many other people answered your question above. This problen arises when your script don't find the jQuery script and if you are using other framework or cms then maybe there is a conflict between jQuery and other libraries.
In my case i used as following-
`
<script src="js_directory/jquery.1.7.min.js"></script>
<script>
jQuery.noConflict();
jQuery(document).ready(
function($){
//your other code here
});</script>
`
here might be some syntax error. Please forgive me because i'm writing from my cell phone. Thanks
Remember that you must first load jquery script and then the script js
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="example.js"></script>
Html is read sequentially!
$ is a function provided by the jQuery library, it won't be available unless you have loaded the jQuery library.
You need to add jQuery (typically with a <script> element which can point at a local copy of the library or one hosted on a CDN). Make sure you are using a current and supported version: Many answers on this question recommend using 1.x or 2.x versions of jQuery which are no longer supported and have known security issues.
<script src="/path/to/jquery.js"></script>
Make sure you load jQuery before you run any script which depends on it.
The jQuery homepage will have a link to download the current version of the library (at the time of writing it is 3.5.1 but that may change by the time you read this).
Further down the page you will find a section on using jQuery with a CDN which links to a number of places that will host the library for you.
(NB: Some other libraries provide a $ function, and browsers have native $ variables which are only available in the Developer Tools Console, but this question isn't about those).

Using JQuery in Drupal 7

I'm writing my own Drupal 7 module, and like to use JQuery in it.
$('#field').toggle();
But I'm getting this error:
TypeError: Property '$' of object [object DOMWindow] is not a function
It seems that JQuery is not loaded. Otherwise $ should be defined.
Though I actually include it in the header:
<script type="text/javascript" src="http://rockfinder.de/misc/jquery.js?v=1.4.4"></script>
Do I have to do anything else to activate JQuery in Drupal? Is $ being overwritten by Drupal?
That's the website: http://rockfinder.orgapage.de
From the Drupal 7 upgrade guide:
Javascript should be made compatible
with other libraries than jQuery by
adding a small wrapper around your
existing code:
(function ($) {
// Original JavaScript code.
})(jQuery);
The $ global will no longer refer to
the jquery object. However, with this
construction, the local variable $
will refer to jquery, allowing your
code to access jQuery through $
anyway, while the code will not
conflict with other libraries that use
the $ global.
You can also just use the 'jQuery' variable instead of the $ variable in your code.
According to Firebug, your jQuery file is being loaded:
But the $ is being overwritten by something else:
What you should do is encapsulate the use of the $ variable with a function that invokes itself using the jQuery object as it's first actual argument:
(function ($) {
// in this function, you can use the $ which refers to the jQuery object
}(jQuery));
Chances are your script is not initialized this way, you'll have to use Drupal.behaviors.YOURTHEMENAME
(function ($) {
Drupal.behaviors.YOURTHEMENAME = {
attach: function(context, settings) {
/*Add your js code here*/
alert('Code');
}
};
})(jQuery);
"$ is not a function" is a very common error that you may face while working with jQuery. You can try any answers of given below:
(function($){
//your can write your code here with $ prefix
})(jQuery);
OR
jQuery(document).ready(function($){
//Write your code here
});
Basically this will allow our code to run and use the $ shortcut for JQuery.
You can create the separate file for js and than add js file using the following:
drupal_add_js('path', 'module_name');

jquery element not defined, but it used to skip it

I recently transferred a site to a new host. Reloaded everything, and the javascript that worked fine before is breaking at an element it can't find. $('#emailForm') is not defined.
Now, the #emailform isn't on the page, but it wasn't before either, and JS used to skip this and it would just work. Not sure why this is happening. Any clues
Here is the site I am having the prblem:
http://rosecomm.com/26/gearwrench/
jQuery will return an empty jQuery object from $('#emailForm') if there isn't an element with the id='emailForm'.
One of the following is likely true:
You forgot to include jQuery - therefore $ is undefined.
There is another library included that uses $ - in which case you can wrap your code in a quick closure to rename jQuery to $
The Closure:
(function($){
// $ is jQuery
$('#emailForm').whatever();
})(jQuery);
You could console.log(window.$,window.jQuery); in firebug to check for both of these problems.
You have mootools-1.2.2-core-yc.js installed as well, and it is conflicting with jQuery.
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
$(document).ready(function() {
(function($){
// bind 'myForm' and provide a simple callback function
$('#emailForm').ajaxForm(function() {
var txt=document.getElementById("formReturn")
txt.innerHTML="<p>Thank You</p>";
});
...
$(document).ready is being called against the moo tools library instead of jQuery.
I'm not sure why it would be skipped before, but to avoid the error, wrap the statement(s) that reference $('#emailForm') in an if statement that checks to see if it is present:
if ( $('#emailForm').length ) {
// code to handle $('#emailForm') goes here...
}

Categories