To call in jquery using namespace - javascript

I am using javascript file and jquery.From my javascript file,I am doing like this:
abc.cde.on({
});
which is calling one widget written in jquery.
abc.cde are namespaces in jquery widget file.
Can anyone please tell how abc.cde.on is calling jquery method without using $ sign before abc.cde

Because cde is already an instance of a jQuery object. You can perfectly store the result of a jQuery selection (or a jQuery widget instance) in an object to reuse it after, see example:
var namespace = {
obj: $('div'),
};
//then you can do:
namespace.obj.on('click', function(){
this.style.color = 'red';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>CLICK ME</div>

Because the $ is already used in previous reference... I suspect abc was defined something like this:
var abc = $('#abc')
So the $ is already referenced...

Related

Include a javascript class in a parent class, rather than in window when it is loaded

For example, we are request jQuery with <script src=". From now on window.jQuery or jQuery will be available.
But I want to prevent it from being used in this way and collect it in a pool.
For example:
container = {
jQuery: (function(){}(), // jQuery' script,
..,
..,
..
};
container.jQuery('.hi').addClass('hello');
container.jQuery(document).on('click', function(){});
Is it possible to do this?
jQuery is just a global variable and as such can be reassigned.
var container = {};
container.jQuery = jQuery;
jQuery = $ = null;
console.log(container.jQuery("div").length);
// gives error $ is not a function:
$("div").css("color", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>a div</div>
.noConflict() allows you to reassign $ back to what it was before jquery was loaded, so you may want to call that first before obliterating $.
You could do it with a module system or call jQuery.noConflict(true). That will give you the jQuery to use as well as reset the globals: https://api.jquery.com/jQuery.noConflict/

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.

How can I determine whether jQuery is fully initialized?

I'm writing a bookmarklet using jQuery. It looks like javascript:document.write('<script src="path/to/loader.js"></script>'), and loader.js does the initializing stuffs:
check_the_environment();
document.head.innerHTML='<meta charset=utf-8>';
document.body.innerHTML='(the webpage)';
var jq=document.createElement('script');
jq.src='path/to/jquery.min.js';
document.head.appendChild(jq);
function load_core() {
if(window.$)
eval('(core js code)');
else
setTimeout(load_core,50);
}
load_core();
The loader loads the core javascript code after the jQuery is available.
But sometimes I get this error in my core code:
$(...).on is not a function
It seems that jQuery was still initializing itself although $ variable is setted.
So, I need to wait for jQuery to be completely initialized before the loader loads the core code. How can I do that?
The traditional way of using $(document).ready(...) is infeasible, as jQuery is being loaded after the webpage is ready.
Here is a minimal Python code to check whether the solution is working:
import cherrypy
mod='''
var htmlroot=document.getElementsByTagName('html')[0];
function load_core() {
if(window.jQuery)
jQuery(function(){
alert($(document).on);
});
else
setTimeout(load_core,10);
}
if(!document.head)
htmlroot.appendChild(document.createElement('head'));
var jquery=document.createElement('script');
jquery.src='http://libs.useso.com/js/jquery/2.1.1/jquery.min.js';
document.head.appendChild(jquery);
load_core();
'''
class Website:
#cherrypy.expose()
def mod(self,_time):
return mod
#cherrypy.expose()
def index(self):
return '''Mod'''
cherrypy.quickstart(Website(),'/');
The right and foolproof way would be:
jQuery(function(){
// code
});
Since jQuery may be loaded in noConflict mode the $ var may not have been initialized.
For the sake of productivity the following can also be used to have access to $ var inside the jQuery scope.
jQuery(function($){
// you can use $ without worrying about conflicts now
});
You can check type of $ as below
if(typeof $ == "function"){
//Jquery loaded
}

Force jQuery to search only in a subtree of a specified element

Is it possible to somehow reconfigure jQuery to search only in a subtree of a specified element?
I need to do something like this:
var lockToSubtree = function (jq) {
//reconfigure jq
return reconfiguredJQuery;
},
myJQuery = lockToSubtree(jQuery, '.my-namespace');
So I have my own instance of jQuery which searches elements only inside '.my-namespace'.
To illustrate my needs here is a sample HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="divOne" class="someClass"></div>
<div class="my-namespace">
<div id="divTwo" class="someClass"></div>
</div>
</body>
</html>
So I can later use in my code:
var $el = myJQuery('.someClass');
And it will search .someClass only in a subtree of a .my-namespace. So it will return only div#divTwo and div#divOne will be skipped because it is not located under a subtree of .my-namespace.
The point is, that I need it to keep searching in a subtree of .my-namespace also when using jQuery functions like .closest() etc., see the final code snippet:
var $myJQuery = lockToSubtree(jQuery, '.my-namespace'),
$el = myJQuery('.someClass'); // $el is the #divTwo element
$el.closest('body'); // finds nothing, because body is not located under .my-namespace
UPDATE:
I agree with #Keith that it is probably not possible to reconfigure jQuery to search in some subtree also with .closest method, which searches upwards. Thus I will be OK with searching in a subtree only when the search direction is down.
I would like to emphasize that I need the jQuery function to have the same functionality like original jQuery (properties like jQuery.fn etc.).
The real life scenario: I need to scope some third party library in our project so it would not affect HTML until some level of depth. The library is a one line of a JavaScript minified code using global jQuery object. All I need is to wrap it in self-invoking function and pass to it some modification of jQuery function which searches only in some subtree of a DOM, but contains all the properties as normal jQuery.
This code maybe explains it better:
(function (jQuery) {
// I am passing jQuery through parameter
// ... here is the library code
}(/* here I want to inject modified jQuery */));
You can create a wrapper function for the jQuery selector like so:
$Q = function (select, opts) {
return $(".my-namespace", opts).find(select);
};
And then just call your wrapper as you would jQuery $Q(".element").children() etc....
jSFiddle here
You can do this with closest to pass a context:
var namespace = $(".my-namespace").get()[0];
$(".foo").closest("p.bar", namespace);
You are asking for something that jQuery does not support, since .closest() will search up the DOM tree all the way to the document. Something terribly expensive, but that will do what you are asking is to clone the .my-namespace into a document fragment. Then, .closest() will not go higher than the document fragment because fragments do not have parents.
I would suggest writing your own .closest() method to make sure you stop where you want, and then use Dormouse's answer for searching down.
I can't accept #Dormouse's or #ArunPJohny's answers because both returns simple functions which do not have another jQuery functions inside like jQuery.fn, so it is impossible to use their solutions.
Here is what I came up after reading #ArunPJohny's code and what works fine for me:
(function (jQuery) {
// third party library using my own modified jQuery function
}((function ($) {
var $wrapper = $('.cms-bootstrap'),
scopedjQuery = function (selector) {
return $(selector, $wrapper);
};
// Copy all jQuery properties into
// scopedjQuery so they can be used later
for (var k in $) {
if ($.hasOwnProperty(k)) {
scopedjQuery[k] = $[k];
}
}
return scopedjQuery;
}(window.jQuery.noConflict()))))

Passing correct jQuery selector to an object

I am writing a jQuery plugin which, ideally I would like in it's own namespace.
So far, this seems to work (in terms of namespace nesting)
(function($) {
$.fn.nspace = {
foo: function() {
// Does not work becuase $(this) is not the correct selector.
$(this).show();
}
}
})(jQuery);
So given then example above, I might call my function like so:
$("html, body").nspace.foo();
but $(this) is not [html, body]...How can I solve this?
EDIT: To clarify (based on user comments)...
$("html, body").nspace.foo(); should call foo for [html, body] but, $(this) inside nspace resolves to nspace...so it's trying to call nspace.foo();
You shouldn't do this, but just because I dislike when someone says "You can't" in programming (often untrue, especially in Javascript) - here's how you could do this:
The jQuery object is constructed each time using its prototype.init function, which is aliased to fn.init, so you could overwrite it with a wrapped function that adds your namespace object in a way that doesn't harm any existing usage or libraries, like so:
(function($) {
var baseInit = $.fn.init;
$.fn.init = function(selector, context, rootjQuery) {
// Instantiate jQuery the way it expects
var j = new baseInit(selector, context, rootjQuery);
// Add our extra object/namespace
// Use j inside to refer to the current jQuery object
j.nspace = {
foo: function() {
j.show();
}
};
// Return it all and other libraries are none the wiser
return j;
}
})(jQuery);
http://jsfiddle.net/b9chris/7TPZY/
You should consider using the classic pattern for a jQuery plugin: define only one method: in your case, nspace. Inside this method, you'll take every case into account. Sounds hard, but it's pretty easy once you've looked into that.
(By the way you definitely have to look at that when writing a jQuery plugin)
You can't add an object as a plugin and still get the jQuery object that was used to get the object. You simply have no reference to that jQuery object when you call a method in your object.
Put the function directly as the plugin:
(function($) {
$.fn.nspace = function() {
this.show();
};
})(jQuery);
Usage:
$("html, body").nspace();
(Note that the object is the jQuery instance, not a selector or an element, so you don't need to use $(this)).

Categories