Enqueueing Javascript and jQuery in a Wordpress plugin - javascript

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(....

Related

Uncaught TypeError: $(...).ddBarChart is not a function

Working on MVC 5 project. This particular page is a partial page (Razor), if that makes any difference.
I'm trying to utilize a ddchart jQuery library. (http://kiersimmons.com/ddchart/index.html) I keep getting this error...
Uncaught TypeError: $(...).ddBarChart is not a function
The line of code that the error is happening on is here:
$("#chart_div_static").ddBarChart({
chartDataLink: "~/Scripts/plugins/ddchart/Chart_Data.js?1=10",
action: 'init',
xOddClass: "ui-state-active",
xEvenClass: "ui-state-default",
yOddClass: "ui-state-active",
yEvenClass: "ui-state-default",
xWrapperClass: "ui-widget-content",
chartWrapperClass: "ui-widget-content",
chartBarClass: "ui-state-focus ui-corner-top",
chartBarHoverClass: "ui-state-highlight",
callBeforeLoad: function () { $('#loading-Notification_static').fadeIn(0); },
callAfterLoad: function () { $('#loading-Notification_static').stop().fadeOut(0); },
tooltipSettings: { extraClass: "ui-widget ui-widget-content ui-corner-all" }
});
I know the function exists and the reference (to the js file that contains the function) is placed before ddBarChart is called. FYI the reference is....
<script src="~/Scripts/plugins/ddchart/jquery.ddchart.js"></script>
As a test: In my jquery.ddchart.js file I even made a test() function that simply pops up an alert. I wrote this function on the line before the ddBarChart function. When I call the test function it works fine. So I know the reference to the external js file (jquery.ddchart.js) is correct.
**** Update ****
FYI: The ddBarChart function, in the external file, starts off as...
jQuery.fn.ddBarChart = function(options) {
function setupDrillDown(strID, intDelay, strH, strW, strL) {
$(strID+ "> .ddchart-chart-final").css("z-index","2");
:
:
}
function aniDrillDown(strID,intDelay) {
$(strID+ " > .ddchart-chart-final > .ddchart-chart-wrapper-sub").animate( {width: "100%",height: "100%",left: "0%"}, intDelay-500, function(){aniCleanUp(strID)});
}
:
:
**** Update Note ****
(This is a MVC 5 partial page (razor), if that makes any difference. Seemed to work when I created a normal non-partial page in a different project.)
Any ideas what this could be? Thanks!
I've encountered a problem like this before. The problem was that the jQuery library was being included twice.
This happened in the following order:
The HTML file loaded the jQuery file, defining the jQuery object.
The HTML file loaded the plugin file, attaching a function to jQuery.fn
The HTML file loaded the jQuery file, redefining the jQuery object.
After this, any references to jQuery will be on the newly defined jQuery object, which does not have the plugin function attached to it.
This would be consistent with it only failing when included from a partial view. You have to ensure the plugin is included only after the single jQuery source is included.

jquery-extension not executing in chrome app

I've encountered a strange problem with my chrome app i'm developing at the moment.
I want to use the "knob" extension to use it for a alarm-clock slider (to set the time)
This wouldn't be a really difficult matter, wouldn't it be for the restrictions and strange issues found while programming a chrome app.
In my index.html file I included the jquery library and the knob extension. And that is where the problems started. Somehow, my scripts only can use the Id's of elements that are above them. So when I include the tags between the tags, nothing executes, if I put them after the first tags they only work with the things that are in this div container. thats why I put the script just before the tag. That works well for "normal" javascript usability. But because I have a that referes to a jquery function (for the knob) the jquery library should be already loaded before the function gets executed (if not, it just doesn't work). I tried to get a workaround by using these posibilities:
document.onload=test();
function test(){
$(function() {
$(".dial").knob();
});
}
document.onload=test();
$(function test() {
$(".dial").knob();
});
}
document.onload=$(function() {
$(".dial").knob();
});
}
well.... It didn't work. I also tried window.onload, with the same reuslt. does someone have a solution? It would be of great help.
Thank you,
neissen
Try like this:
$(function() { //document ready function
function test(){ //inside the ready function
$(".dial").knob();
}
test(); // and call the function here
});
Your Problems:
jQuery may not be loaded but you used some vanilla JS to handle jQuery, which will cause errors.
May be related to global and local.
For the external scripts, functions are only fired locally, which means the global object which contains the html won't be able to be accessed.
To make a global function and a jQuery library - JS:
if ("undefined" === typeof jQuery) {throw new Error("This library requires jQuery"); }
$(function() {
window.myFunction = function() {
doSomething();
}
doSomething();
})
Works calling from HTML - HTML:
<script>
$(function() {
doSomething();
})
</script>
Above is the safest way to approach a jQuery library. The $(function() {... part means exactly the same as $( document ).ready(function() {..., execute if loaded and ready, ensures the browser knows how to deal with all the functions used.

Understanding concept of plugin - $ / jQuery is not defined

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.

$(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).

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