cannot access '$' before initialization error - javascript

I was trying to import a javascript file to another javascript file using jquery but I keep on running into the error $(document).ready(function () { ReferenceError: Cannot access '$' before initialization my current code is attached below. I included the $.getScript function inside $(document).ready(function()) { because I was trying to initialize jquery before $ assignment. Thanks in advance.
Current Code for trying to import js file
$(document).ready(function () {
//your code here
$.getScript("index.js", function(){
function time(){
alert("the time is" + h)
}
});
});

Related

jQuery plugin's $ collides with jQuery's $

I have 3 js files, call them myJavascript.js, myPlugin.js and the jQuery libary.
The files themselves are relatively long, so I try to convey the issue without copying the entire scripts.
In the html file using them, I've included the js files in the following order:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="resources/js/myPlugin.js"></script>
<script src="resources/js/myJavascript.js"></script>
I've written the plugin in the following structure:
myPlugin.js :
(function ($) {
local variables...
//several functions with the form
$.fn.funcName = function(parameters) { body };
//several function used internally
function funcName(parameters) { body }
}(jQuery));
In myJavascript.js, I'm using only methods defined in the plugin (just like using jQuery methods), and it's working. However, when I tried to invoke a jQuery method (authentic one, not from the plugin) before invoking plugin function, I got the error:
Uncaught TypeError: $(...).mazeBoard is not a function
To give a concrete example:
/* when this block exists, the call to mazeBoard throws the error */
/* when I remove this block, the call to mazeBoard works perfectly */
{
$(function () {
jQuery("#navigationMenu").load("nav.html");
loadSettings();
});
}
/********************/
{
...local variables...
function getSingleGame() {
...body...
$.getJSON(url, function (data) {
//this is some function in myJavascript.js
var mazeData = makeMazeData(data.Maze, data.Rows, data.Cols);
//this is call to function from my plugin
mymaze = $('#mazeCanvas').mazeBoard(mazeData);
alert('success');
}).fail(function () {
alert('error!');
});
}
}
Anyone knows what's the problem? If everything seems to be fine, I'll try to add more details.

Why Javascript $(document.body) does not load outside of the source file?

First of, a quick word about my setup.
I have a global JS file common.js, where I store all commonly used functions. This file is bundled and set to load along with _Layout.cshtml view file.
Along with that, I have a view file, which generates an html object like following:
<a class="printreport" href="#" data-reporttype="8" data-certid="1111">Print</a>
Mentioned view file loads javascript source file through extended method
#section scripts {
#Html.LoadVersionedJavascriptFile("~/location/sourcefile.js")
}
In order to optimize my code, I decided to write a snippet function, which will make every html object with "printreport" class run it
Inside source file:
$(function(){
//other stuff
//Every html object that has printreport as a class will run this function
$(document.body).on('click', '.printreport', function () {
//get reporttype data from object
var reportType = $(this).data('reporttype');
var link = $("#RootDirectory").val();
switch (reportType) {
//other cases
case 8: //Certification
var certId = $(this).data('certid'); //Get certid data from object
link += '/Reports/ReportPopUp.aspx?report=' + reportType + '&CertId=' + certId;
break;
}
//code
});
});
Inside the source file, it responds and works as intended. However, if I try moving that snippet from the source.js into a global common.js (I confirmed that file is loaded during execution), it simply does not respond, and clicking on link does nothing:
Inside common.js file:
//declaration of global variables
$(document).ready(function () {
}
$(document.body).on('click', '.printreport', function () {
//code
}
Structure of common.js file is as above, it is not encapsulated into anything.
My question is: Am I loading document.body part improperly? What could be the possible cause of such unresponsiveness?
You should move your click handler inside $(document).ready:
$(document).ready(function () {
$(document.body).on('click', '.printreport', function () {
//code
}
}
$(document).ready is an event which fires up when document is ready and since your html is interpreted from top to bottom, your elements could not be present when your jQuery code runs ($(document.body)).

Broserify exported function error: is not a function

I have a module "./lib/common.js", like this:
function foo(text){
console.log(text);
}
function boo(text){
console.log(text);
}
module.exports=foo;
module.exports=boo;
I'm trying to include these functions in another js file using browserify :
var common =require('./lib/common.js');
$(document).ready(function() {
common.foo('hi');
});
Browserify creates the bundle,but on the browser I get
Uncaught TypeError: common.foo is not a function
Ok this was very stupid, I was overwriting my module.exports with the last row module.exports=boo;
With this change it works:
module.export.foo=foo;
module.export.boo=boo;

How can I use a javascript function globally in Drupal 7

How can I use a javascript function globally in Drupal 7.
I have my javascript file set up like this and add it using drupal_add_js():
(function($) {
function add_if_country_is_not_usa() {
// Check what country it is
// Update text, image, etc.. of a block.
}
});
In my block WYSIWIG I added the following code (The reason I add it in the WYSIWIG is because I want it to update before the page is fully rendered):
<script type="text/javascript">
add_if_country_is_not_usa();
</script>
But I get the following error:
Uncaught ReferenceError: add_if_country_is_not_usa is not defined
(anonymous function)
I read about adding functions to Drupal behaviors but that happens on document ready. I want to run the function as soon as the block is shown.
Any ideas?
Either define in the global scope, or do like below:
(function($) {
function add_if_country_is_not_usa() {
// Check what country it is
// Update text, image, etc.. of a block.
}
// set as a property of the global object `window`
window.add_if_country_is_not_usa = add_if_country_is_not_usa;
});
Not sure if this is the best way but I ended up being able to get it work using a namespaces. I call myGlobalObject.add_if_country_is_not_usa() from my block and it works now.
var myGlobalObject = mySingleGlobalObject || { 'country': {} };
(function ($) {
myGlobalObject.country = '';
myGlobalObject.add_if_country_is_not_usa = function() {
// Check what country it is
// myGlobalObject.country = 'US';
}
})(jQuery);

calling a method which is in different file

In my project, I have two js files which are as follows:
file1.js
(function($){
jQuery(function(){
jQuery.user = {
getAnchorUrl : function (el){
return jQuery(el).attr('href');
}
}
});
})(jQuery);
file2.js
(function($){
jQuery(function(){
jQuery('.popup-video-link').on('click', function(e){
e.preventDefault();
var url = jQuery.user.getAnchorUrl(this);
jQuery.user.getVideoPopupTemplate(url);
});
});
})(jQuery);
I am loading file1.js first then file2.js.
Whenever I click the anchor tag which has class .popup-video-link, I am getting error
TypeError: jQuery.user.getAnchorUrl is not a function
Any help where I am going wrong?
PS: I am wrapping the jquery code because in this project I am also using prototype.js and many other plugins.
Remove jQuery(function(){ from file1.js. Try this:
(function($){
jQuery.user = {
getAnchorUrl : function (el){
return jQuery(el).attr('href');
}
}
})(jQuery);
When using jQuery(callback) the call back is loaded when the page is loaded (like $(document).ready(callback), almost), (callback)(jQuery) creates an anonymous function which is then called with the first parameter as jQuery

Categories