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>
Related
I have a function that works on the body onload="" but I need it to load before other elements of the page and I'm trying to add the document ready function in the header but it just doesn't seem to work.
f1menu() {
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'},333)
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333)
}
);
}
$(document).ready(function() {
f1menu();
});
So the onload function that works is just this one below:
onload="$('.menuH').hover(function() {$('.menuC').stop().animate({width: '90px'}, 333)}, function() {$('.menuC').stop().animate({width: '-0'}, 333)});"
Note that the following answer was provided before the OP changed the question.
You should write:
function f1menu(){}
not,
f1menu(){}
In addition, you can streamline your document.ready code by simply passing the function that you want called when the document is ready, directly to jQuery:
$(function() {
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'}, 333);
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333);
}
);
});
UPDATE:
After OP revised the question, the solution (not a recommended approach by the way) would be to just insert the script into the body of the page, but AFTER any elements that the function references, such as:
<body>
<!-- elements that the code references must come before the code -->
<script>
// .menuH and .menuC elements must have already been loaded into DOM
$('.menuH').hover(
function() {
$('.menuC').stop().animate({width: '90px'},333)
},
function() {
$('.menuC').stop().animate({width: '-0'}, 333)
}
);
</script>
<!-- Rest of HTML -->
</body>
It doesnt know f1menu is a function since you didnt declare it as one. Try this:
function f1menu(){
//logic
}
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
}
});
I have a javascript function that i have named refreshProjects(), what it does is filter a dropdownlist depending on what was selected in a previous dropdownlist. But i need to also filter my list direcktly after the page has finishd loading.
I have tried using the code window.onload = refreshProjects(id) with no sucsses, but onload workes when i use window.onload = alert('This page has finished loading!'), so i know that part off the script works. So how do i call a javascript function on load, i thought that it would be simple but evrything i tried have failed.
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
window.onload = refreshProjects(id); <-- Problem
$("#ddCustomers").change(function () {
refreshProjects($(this).val());
});
function refreshProjects(id) {
var projects = $("#ddProjects");
$.get('#Url.Action("FilterProjects","TimeEntry")', { customerId: id },
function (result) {
// clear the dropdown
projects.empty();
//Add a deafult "null" value
$("#ddProjects").get(0).options[0] = new Option("[ - No project - ]", "-1");
// rebuild the dropdown
$.each(result, function (i, e) {
projects.append($('<option/>').text(e.Text).val(e.Value));
});
});
}</script>
}
This is for MVC 4.5.
Try changing window.onload = refreshProjects(id); to:
window.onload = function() { refreshProjects($("#ddCustomers").val()); };
Onload expects a callback function. You were directly executing refreshProjects() and setting the return value as the onload.
But since you seem to be using jQUery, you could do the following:
$(function() {
refreshProjects($("#ddCustomers").val());
});
This will execute refreshProjects when the document is ready (which actually is before window load).
You can also try to use the following:
$(document).ready(function () {
refreshProjects(id);
});
This should work aswell if you are using jQuery.
I have a js function which looks like this
function showProducts(){
document.getElementById("shopList").innerHTML = "<ul><li>Test Text</li></ul>";
}
It's a function that has to show an array of my products. I've made an div with id="shopList" in my html page
<div id="shopList">
</div>
But how can I call the function to show me the text in the div? It works when I use this as my body tag but I'm not allowed to write any js code in my html or to use onload or onclick. I'm trying to do it with listeners for almost 4 hours and I still did not find a solution. Could someone help me?
<body onload="showProducts()">
Using pure javascript:
window.onload = function(){
};
(or
function doLoad() {
//Do stuff on load
}
window.onload = doLoad;
With Jquery
$(document).ready(function(){
});
It's not difficult with listeners. Here is a solution (not cross-browser):
document.addEventListener("DOMContentLoaded", showProducts);
Really, assigning to onload is just shorthand for doing it with listeners. This should work , though I haven't tested it.
window.addEventListener("load", showProducts);
With Jquery you could do something like this :
$(document).ready(function(){
showProducts();
});
It waits untill the page is loaded and then executes the function.
You just put it in an external .js file and include it in your page.
(For the people downvoting this answer because it's Jquery, he said he couldn't use onload() so I just mentioned this option. )
Just place the script at the bottom:
<body>
...
<script type="text/javascript">
myFunction();
</script>
</body>
John Resig's simplified version from "Pro JavaScript Techniques". It depends on addEvent.
var ready = ( function () {
function ready( f ) {
if( ready.done ) return f();
if( ready.timer ) {
ready.ready.push(f);
} else {
addEvent( window, "load", isDOMReady );
ready.ready = [ f ];
ready.timer = setInterval(isDOMReady, 13);
}
};
function isDOMReady() {
if( ready.done ) return false;
if( document && document.getElementsByTagName && document.getElementById && document.body ) {
clearInterval( ready.timer );
ready.timer = null;
for( var i = 0; i < ready.ready.length; i++ ) {
ready.ready[i]();
}
ready.ready = null;
ready.done = true;
}
}
return ready;
})();
window.onload would work, but it is a different beast. jQuery's $(document).ready() is much more complex and better in most scenarios.
Given your criteria of "no script in the HTML" and "no onload or onclick listener", you can put the function into a separate file and run it from a script element at the foot of the page:
<script type="text/javascript" src="showproducts.js"></script>
so now you have no script in the page and no listeners. The code will be executed when the element is added to the DOM, so as long as it is after the related DIV, you're fine.
Incidentally, you don't even need a function, you can just put the statements from the function body into the file.
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!