calling a method which is in different file - javascript

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

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.

How to call javascript function inside jQuery

We have this tag with a javascript function in our HTML,
<select name="My_Saved_Billing" onchange="Choose_My_Saved_Billing(this.selectedIndex)" >
<option>Select</option>
<option value="1714">Address line 1, QC</option>
</select>
<script type="text/javascript">
function Choose_My_Saved_Billing(arg_index) {
switch(arg_index) {
// some commands here
}
}
</script>
And I also added a jQuery to it which is below so that on windows load, it will automatically select the second option.
<script type="text/javascript">
$(window).load(function(){
$("select").val($("select option:eq(1)").val());
});
</script>
But is it possible to call javascript function using jQuery? If so, how should I call this one?
Should I use Choose_My_Saved_Billing(this.selectedIndex)or Choose_My_Saved_Billing(arg_index)or you might know something. I've tried these two but none are working. Please let me know. Just a beginner here.
The way to call a JavaScript function from a JQuery file is the same as calling a JavaScript function from a JavaScript file :) This is so because JQuery is a library based from JavaScript. Say, you want to call function foo from a JavaScript file, when the window loads.
JQuery:
$(window).on('load', function() {
foo();
});
And JavaScript:
function foo() {
alert('This works!');
}
I hope this helps!
Yes, it's possible to call functions inside a jQuery ready block. Since you've defined the function at global scope (should probably move this into the jQuery ready block or, if you want to go to the trouble, into a module), it can be called from anywhere. So inside your ready block:
$(function () {
// do stuff
Choose_My_Saved_Billing(args);
});
jQuery is JavaScript. It's just a library for JavaScript. The main jQuery global $ is a JavaScript function that takes a valid selector as an argument and provides several methods on the return value of that function.
So calling a JavaScript function inside the callback function to .load is not an issue.
It is not clear what the Choose_My_Saved_Billing function actually does.
Think about what's happening here. In your onchange event you're calling the function with the index of the selected option passed as an argument. Since JQuery is just a library of shortcuts for things you can do in JavaScript, we should easily be able to do the same thing.
So let's get the element for which we want the selected index:
// maybe think about adding an ID here for better selection
var select = $('select[name^="My_Saved_"]');
Then let's get the index with a change event, then call the function:
var index = 0;
select.change(function(){
index = select.selectedIndex || 2; // set the index to default to 2
Choose_My_Saved_billing(index);
});
Instead of using onchange="...", just use jQuery to attach a change listener:
$(window).load(function() {
$('.colors_backgroundneutral select').on('change', function () {
Choose_My_Saved_Billing(this.value);
});
});
$(document).ready(function() {
$("#Submit1").click(function() {
$("#id1").hide();
Raise1();
});
$("#Raise").click(function() {
$("#id1").show();
});
});
function Raise1() {
var value1;
alert("hi");
value1 = document.getElementById("amount").value;
alert(value1);
alert("done");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
As jQuery is a more simple and advanced JavaScript solution, my guessing is you can call you JS function like this:
$(window).load(function(){
my_js_function(arg1, arg2);
});
Now, what you want is to call the JS function named Choose_My_Saved_Billing() with argument arg_index
So, your jQuery will look like this:
$(window).load(function(){
Choose_My_Saved_Billing(arg_index);
});
This only works if the function is already declared through raw code, on via the <script type="text/javascript" src="path/to/my_file.js"> head tag.
It should work like a charm, if not, feel free to share the errors returned by your browser.

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

fake jquery document.ready calls on pages without jquery

I wanted to use some data in another JS script which had a JQuery call $(document).ready(function() inside the block, but i did not want to use JQuery nor init the script, because i just wnat to use some of the predefined variables.
So simply using the script from external source ( as it might get changed ) but skipping the ready() call and just do some data manipulation afterwards.
I got it working with
<script>
var fakeJquery = function(fn) {
this.ready = function () {
return true;
}
};
var $ = function(fn) { return new fakeJquery();}
</script>
But i wonder if there is a better, easier way to do that?

method is not defined in Javascript when I use Web Logger for iOS

It's really strange when I try to dump logs to the Web page.
I have basic application (in xcode) with Web plugin that allows me to pull logs from iPhone to web page.
But, somehow, when I try to call method placed in other js file, I get:"method" is not defined.
xcode-Web structure:
Snippets of socket.html:
<script type="text/javascript" src="src/js/script.js"></script>
<script type="text/javascript">
$(document).ready(main);
// Run when document.ready fires
function main() {
$('#btnClear').click(function() {
clearTable();
});
}
....
</script>
The clearTable is method defined in src/js/script.js file and I know its loaded because onLoad method has called.
Snippets of script.js:
$(function() {
....
function onLoad(){
....
}
function clearTable(){
....
}
onLoad();
});
Does someone know the reason?
I coped this project to linux and all work fine. All dependences work good.
Thank you,
It is because of scoping issue, clearTable is defined within an anonymous function so it will be available only within that scope.
You are trying invoke it from another scope where it is not available.
The solution is to define the clearTable in the global scope. ex
$(function() {
// ....
function onLoad() {
// ....
}
window.clearTable = function() {
// ....
}
onLoad();
});
Problem: Fiddle
Solution: Fiddle
Another solution
var clearTable, isAutoScroll; //Declare these as global variables
$(function() {
// ....
function onLoad() {
// ....
}
//note this is a function variable and there is no `var`
clearTable = function() {
// ....
}
//note there is not `var` used while defining the variable
isAutoScroll = false;
onLoad();
});

Categories