I'm creating namespaces for my project and I want to call a function within jQuery(document).ready().
Using the self encapsulated jQuery namespace structure I'm able to make the example work.
But once I move MYNAMESPACE.myFunction();inside jQuery(document).ready(), it's not working any more.
This is probably because of some jQuery logic that I don't understand. Can anyone push me in the right direction please? Here is my fiddle.
Code:
//HTML
<div class="test"> test </div>
//JS
jQuery(document).ready(function($) {
if($('.test').text().length > 0){
MYNAMESPACE.myFunction(); //function call
}
});
;var MYNAMESPACE = {};
;(function($) {
MYNAMESPACE = {
myFunction: function()
{
$('.test').text('Text changed');
}
}
})(jQuery);
// MYNAMESPACE.myFunction(); //<-- This works
The code in your fiddle is executed on window.load. Which means that the document is ready when you make that call and jQuery synchronously executes the callback. At that point, you haven't defined MYNAMESPACE.
It works if you specify that you don't want the code to execute on window.load: http://jsfiddle.net/baT47/
Or if you define MYNAMESPACE first: http://jsfiddle.net/c8L7c/
;var MYNAMESPACE = {};
;(function($) {
MYNAMESPACE = {
myFunction: function()
{
$('.test').text('Text changed');
}
}
})(jQuery);
// MYNAMESPACE.myFunction(); //function call
jQuery(document).ready(function($) {
if($('.test').text().length > 0){
MYNAMESPACE.myFunction(); //function call
}
});
Related
I have some legacy jQuery executing in the page that can't be moved i.e.
jQuery(document).bind('click', function(){
console.log('click');
});
Now that loading of jQuery is at the bottom of the page 'AFTER' the above inline code, the page errors 'jQuery is undefined'
I would like to use a pattern similar to this:
var deferInlineScripts = [];
window.$ = function(inlineFunction) {
deferInlineScripts.push(inlineFunction);
};
Seen working here: https://jsfiddle.net/xpvt214o/165864/
that takes the inline scripts and executes them (Once jQuery is loaded') using
for (i = 0; i < deferInlineScripts.length; i++) {
deferInlineScripts[i]();
}
But unlike the Fiddle my legacy code doesn't have the $(function(){}); and can't be moved, changed or have anything wrapped around it i.e
jQuery(document).bind('click', function(){
console.log('click');
});
jQuery(document).ready(function(){
console.log('ready');
});
Here is the Fiddle https://jsfiddle.net/xpvt214o/165972/ that I would like to fix so the the Bind & Ready functions execute after jQuery is loaded.
Initially define window.jQuery as a function that returns a Proxy. This proxy will allow subsequent arbitrary psuedo-propery lookups (such as .bind in jQuery(document).bind) to be performed. The properties accessed and the arguments the resulting function is eventually called with can be stored in an array and then executed once jQuery is properly loaded.
<script>
const deferCallHandler = {
get: function(jqFirstArg, jqProp) {
return function(...secondArgs) {
deferredInlineScripts.push({
jqFirstArg,
jqProp,
secondArgs,
});
}
}
};
const deferredInlineScripts = [];
window.jQuery = function(jqFirstArg) {
return new Proxy(jqFirstArg, deferCallHandler);
}
document.addEventListener('DOMContentLoaded', function(){
// window.jQuery has now been properly assigned to the true jQuery object
deferredInlineScripts.forEach(({ jqFirstArg, jqProp, secondArgs }) => {
jQuery(jqFirstArg)[jqProp](...secondArgs);
});
});
/* Can't change this code */
jQuery(document).bind('click', function(){
console.log('click');
});
jQuery(document).ready(function(){
console.log('ready');
});
</script>
<div>some element</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have two files - main, and events. I'm trying to call some function from one file to another.
So, this is how it looks:
events
require(['app/main'], function(call) {
// click event respond test
document.body.addEventListener("click", function(e) {
var target = e.target;
if (target.hasClass === "call"){
functionCall()();
}
});
});
main
define(["jquery"], function() {
// Call
var box = $('.box');
return function functionCall(){
box.addClass('visible');
}
});
What is wrong, can anyboyd help?
main:
define(["jquery"], function($) {
var main = {
functionCall: function(){
$('.box').addClass('visible');
}
}
return main;
});
events:
require(['jquery','app/main'], function($, main) {
$('body').on('click', function () {
if($(this).hasClass('call')){
main.functionCall();
}
});
});
One way is to add this code where you need to make call to function:
require('pathToModuleOrModuleName').functionYouWantToCall()
But if you have module defined or required in the beggining (as 'main' in the events), then in place where call to function needed just add:
call.functionName();
Unless my eyes deceive me the simplest change to make to your code would be to replace this:
functionCall()();
with this:
call();
since the function that the main module returns is imported as call in your events module, because that's how you name it in the callback passed to define.
Firstly your code has some basic problems
In the following code
define(["jquery"], function() {
Where are you referring the query inside the function definition.
I think you should first map the jquery defined into the function declaration like below
define(["jquery"], function($) {
Secondly, what is the () doing after the calling function?
if (target.hasClass === "call"){
functionCall()();
}
Remove the trailing () from that call. It should just be functionCall();
I am trying to work out how to call functions within my jQuery plugin from outside the plugin. The code I have tried is not working. I'm sure I will have to restructure my plugin to allow this, but I'm not sure how to. In this example, I'm trying to access the underline() function.
jsFiddle
jQuery plugin
(function($) {
"use strict";
$.fn.testPlugin = function(options) {
// Settings
var settings = $.extend({
newText : "Yabadabado"
}, options);
return this.each(function(i, el) {
var init = function(callback) {
if( $(el).attr("class") === "red" ) {
$(el).css("color","red");
}
$(el).text(settings.newText);
if( callback && typeof(callback) === "function" ) {
callback();
}
};
var underline = function() {
$(el).addClass("underline");
};
init();
});
};
}(jQuery));
Assign the plugin to selectors
var doTest = $("#testItem").testPlugin({
newText: "Scoobydoo"
});
var doNewTest = $("#newTestItem").testPlugin({
newText: "kapow!"
});
Call a function that is located within the plugin
$("#underline").click(function(e) {
e.preventDefault();
doTest.underline();
});
Take a look at closures.
Here is a basic example of what a closure looks like in a jQuery plugin.
$.fn.plugin = function() {
return {
helloWorld: function() {
console.log('Hello World!');
}
}
};
// init plugin.
var test = $('node').plugin();
// call a method from within the plugin outside of the plugin.
test.helloWorld();
You can see another example at the following jsfiddle.
http://jsfiddle.net/denniswaltermartinez/DwEFz/
First thing first we need to understand each step in building a jQuery plugin, its like build a javascript plugin (class) but we have in addition to it a jQuery class.
//We start with a function and pass a jQuery class to it as a
//parameter $ to avoid the conflict with other javascript
//plugins that uses '$ as a name
(function($){
//We now append our function to the jQuery namespace,
//with an option parameter
$.fn.myplugin = function(options) {
//the settings parameter will be our private parameter to our function
//'myplugin', using jQuery.extend append 'options' to our settings
var settings = jQuery.extend({
param:'value',
}, options);
//Define a reference to our function myplugin which it's
//part of jQuery namespace functions, so we can use later
//within inside functions
var $jquery=this;
//Define an output object that will work as a reference
//for our function
var output={
//Setup our plugin functions as an object elements
'function1':function(param){
//Call jQuery reference that goes through jQuery selector
$jquery.each(function(){
//Define a reference of each element of jQuery
//selector elements
var _this=this;
});
//This steps is required if you want to call nested
//functions like jQuery.
return output;
},
//If we want to make our plugin to do a specific operations
//when called, we define a function for that
'init':function(){
$jquery.each(function(){
var _this=this;
//Note that _this param linked to each jQuery
//functions not element, thus wont behave like
//jQuery function.
//And for that we set a parameter to reference the
//jQuery element
_this.$this=$(this);
//We can define a private function for 'init'
//function
var privatefun=function(){}
privatefun();
//We can now do jQuery stuffs on each element
_this.$this.on('click',function(){
//jQuery related stuffs
});
});
//We can call whatever function we want or parameter
//that belongs to our plugin
output.function1("value");
}
};
//Our output is ready, if we want our plugin to execute a
//function whenever it called we do it now
output.init();
//And the final critical step, return our object output to
//the plugin
return output;
};
//Pass the jQuery class so we can use it inside our plugin 'class'
})(jQuery);
Using our function now is very easy
<div class="plugintest">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
<script>
$(function(){
var myplugin=$(".plugintest > span").myplugin({
param:'somevalue'
});
myplugin.function1(1).function1(2).function1(3);
});
</script>
In short, jQuery plugins and any Javascript plugins are simply about parameters scope.
Fiddle version
https://jsfiddle.net/eiadsamman/a59uwmga/
I want to add a function to jQuery UI Dialog. I want to do that without actually downloading .js file with jQuery UI Dialog source code and editing it. Is it possible to do this from separate .js file?
Some further explanation: let's say I want to add custom function that's called e.g. "func1". After I've coded it, I should be able to call it like this:
($"#dialog").dialog("func1");
Is that possible without editing original jQuery Dialog source code?
Ok, I've finally found the answer :D
(function($){
var _init = $.ui.dialog.prototype._init;
//Init
$.ui.dialog.prototype._init = function() {
var self = this;
_init.apply(this, arguments);
//here you can do custom init
};
//Custom Dialog Functions
$.extend($.ui.dialog.prototype, {
func1: function() {
alert("f1");
},
func2: function() {
alert("function 2");
}
});
})(jQuery);
I have figured it out from this post :
http://www.droptoframe.com/?p=35
I have not tested, but I think it should work:
$.fn.dialog = (function() {
var cached_function = $.fn.dialog;
return function() {
if (arguments[0] !== "func1")
cached_function.apply(this, arguments);
else {
// Do what you want here...
}
};
}());
How can i call a jQuery function from javascript?
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
});
//just js
function js_fun () {
my_fun(); //== call jquery function
}
Yes you can (this is how I understand the original question).
Here is how I did it. Just tie it into outside context.
For example:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
I encountered this same problem when trying to access methods of the object, that was instantiated
on DOM object ready only. Works. My example:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
now you can use something simple like:
function() = {
MyCtrl.update(); // yes!
}
You can't.
function(){
function my_fun(){
/.. some operations ../
}
}
That is a closure. my_fun() is defined only inside of that anonymous function. You can only call my_fun() if you declare it at the correct level of scope, i.e., globally.
$(function () {/* something */}) is an IIFE, meaning it executes immediately when the DOM is ready. By declaring my_fun() inside of that anonymous function, you prevent the rest of the script from "seeing" it.
Of course, if you want to run this function when the DOM has fully loaded, you should do the following:
function my_fun(){
/* some operations */
}
$(function(){
my_fun(); //run my_fun() ondomready
});
// just js
function js_fun(){
my_fun(); //== call my_fun() again
}
var jqueryFunction;
$().ready(function(){
//jQuery function
jqueryFunction = function( _msg )
{
alert( _msg );
}
})
//javascript function
function jsFunction()
{
//Invoke jQuery Function
jqueryFunction("Call from js to jQuery");
}
http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/
<script>
// Instantiate your javascript function
niceJavascriptRoutine = null;
// Begin jQuery
$(document).ready(function() {
// Your jQuery function
function niceJqueryRoutine() {
// some code
}
// Point the javascript function to the jQuery function
niceJavaScriptRoutine = niceJueryRoutine;
});
</script>
jQuery functions are called just like JavaScript functions.
For example, to dynamically add the class "red" to the document element with the id "orderedlist" using the jQuery addClass function:
$("#orderedlist").addClass("red");
As opposed to a regular line of JavaScript calling a regular function:
var x = document.getElementById("orderedlist");
addClass() is a jQuery function, getElementById() is a JavaScript function.
The dollar sign function makes the jQuery addClass function available.
The only difference is the jQuery example is calling the addclass function of the jQuery object $("#orderedlist") and the regular example is calling a function of the document object.
In your code
$(function() {
// code to execute when the DOM is ready
});
Is used to specify code to run when the DOM is ready.
It does not differentiate (as you may think) what is "jQuery code" from regular JavaScript code.
So, to answer your question, just call functions you defined as you normally would.
//create a function
function my_fun(){
// call a jQuery function:
$("#orderedlist").addClass("red");
}
//call the function you defined:
myfun();
I made it...
I just write
jQuery('#container').append(html)
instead
document.getElementById('container').innerHTML += html;
//javascript function calling an jquery function
//In javascript part
function js_show_score()
{
//we use so many javascript library, So please use 'jQuery' avoid '$'
jQuery(function(){
//Call any jquery function
show_score(); //jquery function
});(jQuery);
}
//In Jquery part
jQuery(function(){
//Jq Score function
function show_score()
{
$('#score').val("10");
}
});(jQuery);
My problem was that I was looking at it from the long angle:
function new_line() {
var html= '<div><br><input type="text" value="" id="dateP_'+ i +'"></div>';
document.getElementById("container").innerHTML += html;
$('#dateP_'+i).datepicker({
showOn: 'button',
buttonImage: 'calendar.gif',
buttonImageOnly: true
});
i++;
}
<script>
$.myjQuery = function() {
alert("jQuery");
};
$(document).ready(function() {
alert("Welcome!");
});
function display() {
$.myjQuery();
};
</script>
<input type="button" value="submit" onclick=" display();">
Hope this will work for you!