If JQuery does exist in scope will these behave in the same way?
The $ is used to constrain the scope to inside each function I guess, I'm not exactly sure why however. The second snippet is the original code, I'm attempting to add a check for jquery before it's called as in the first snippet.
First:
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
main(jQuery);
})();
function main($, undefined) {
alert("main 1");
//do some work on $
}
Second:
(function ($) {
if (!$) {
alert('Error: JQuery not loaded.');
return;
}
alert("main 2");
//do some work on $
})(jQuery);
Third (Maybe this is slightly better?):
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
var main = function ($, undefined) {
alert("main 3");
//do some work on $
}
main(jQuery);
})();
This is the best solution for me.
(function () {
if (!window.jQuery) {
alert('Error: JQuery not loaded.');
return;
}
var main = function ($, undefined) {
alert("main 3");
//do some work on $
}
main(jQuery);
})();
Related
I've got a function which I've assigned to a variable and when I instantly invoice it with IFFE, I get an undefined error.
<script>
"use strict";
$(document).ready(function () {
var enableBulkAction = function () {
if ($("#frmProductManagement input:checkbox:checked").length > 0) {
// any one is checked
$('#ddlBulkAction').prop("enabled", "enabled");
} else {
// none is checked
$('#ddlBulkAction').prop("disabled", "disabled");
}
}();
$('#chkTableAll').click(function () {
var checkedStatus = this.checked;
$('#tblProductsManagements tbody tr').find('td:first :checkbox').each(function () {
$(this).prop('checked', checkedStatus);
enableBulkAction();
});
});
});
</script>
enableBulkAction(); is not a function even though it should be in scope. Anyone know what I've forgotten to do?
What you will want to do to change this, if you want the enableBulkAction to be available for reference AND you want to invoke it right away is to make this change:
var enableBulkAction = function () {
if ($("#frmProductManagement input:checkbox:checked").length > 0) {
// any one is checked
$('#ddlBulkAction').prop("enabled", "enabled");
} else {
// none is checked
$('#ddlBulkAction').prop("disabled", "disabled");
}
};
enableBulkAction();
The rest of the script can remain as is.
I have the following code in one of my websites. I have a declared function named "pressedTab(tab)".
When i try to call it inside the following animate complete function, $('#firstShow').animate({'margin-left':'-='+go+'px'}, 1000, 'linear',function() {...pressedTab(tab);} it's not working.
I know its a scope thing but can someone help me fix the code? The strange part is that this code for years it worked. The last year it's not working properly.
<script type="text/javascript">
$(document).ready(function () {
$('.tab1').click(function () {
name('tab1');
});
$('.tab2').click(function () {
name('tab2');
});
$('.tab3').click(function () {
name('tab3');
});
function name(tab) {
function pressedTab(tab) { //FUNCTION THAT I NEED HELP WITH
if (tab == 'tab1') {
$('#img-2 #folder-tab-3').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexDown');
$('#folder-tab-1').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexUp');
$('#folder-tab-2').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexDown');
$('.tab1 p').removeClass('current').addClass('current');
$('.tab2 p').removeClass('current');
$('.tab3 p').removeClass('current');
$('#tug').hide('fast');
$('#tugImages').hide('fast');
$('#vessels').show();
$('#vessels2').hide(0);
} else if (tab == 'tab2') {
$('#img-2 #folder-tab-3').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexDown');
$('#folder-tab-1').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexDown');
$('#folder-tab-2').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexUp');
$('.tab1 p').removeClass('current');
$('.tab2 p').removeClass('current').addClass('current');
$('.tab3 p').removeClass('current');
$('#tug').hide('fast');
$('#tugImages').hide('fast');
$('#vessels').hide(0);
$('#vessels2').show();
} else {
$('#img-2 #folder-tab-3').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexUp');
$('#folder-tab-1').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexDown');
$('#folder-tab-2').removeClass('zindexUp').removeClass('zindexDown').addClass('zindexDown');
$('.tab1 p').removeClass('current');
$('.tab2 p').removeClass('current');
$('.tab3 p').removeClass('current').addClass('current');
$('#tug').show();
$('#tugImages').show();
$('#vessels').hide(0);
$('#vessels2').hide(0);
}
}
if ($('#firstShow').attr('time') == "0") {
var go = "250";
$('#firstShow').animate({
'margin-left': '-=' + go + 'px'
}, 1000, 'linear', function () {
$(this).attr('time', "1");
$('.tab1').attr('time', "1");
$('.tab2').attr('time', "1");
$('.tab3').attr('time', "1");
//Show the right folder
$('#folder-tab-1').show("fast");
$('#folder-tab-2').show("fast");
$('#img-2 > #folder-tab-3').show("fast");
//Hide the Upper of the folder
$('#img-1').hide("fast");
$('#firstShow #folder-tab-3').hide("fast");
//alert(tab);
pressedTab(tab); //FUNCTION WHERE I WOULD LIKE TO BE CALLED BUT IT'S NOT
});
} else {
pressedTab(tab);
}
}
});
</script>
Callback function in animate(...) will be call after name(tab) in context which do not have access to scope of name(tab) function, but it have access to global scope. Try to put pressedTab(tab) outside $(document).ready(...) it should work.
I wrote this plugin to catch show event only for div_loading_page element:
(function ($) {
$.each(['show'], function (i, ev) {
var el = $.fn[ev];
$.fn[ev] = function () {
this.each(function () {
if (this.id == 'div_loading_page') {
$(this).trigger(ev);
return false; // break out of the loop
}
});
//alert(this.id);
el.apply(this, arguments);
};
});
})(jQuery);
It's working fine but because of it i get following error:
$cluetipTitle.show() is undefined , which is from cluetip jquery plugin. Any idea how can i resolve this conflict?
Change:
el.apply(this, arguments);
To
return el.apply(this, arguments);
This ensure that the original function's return value is reserved and will not cause unexpected behavior
change this
$.each(['show']
to
return $.each(['show']
this will allow for chaining, ie doing what you want to do with the .show
I am getting this error:
ReferenceError: overlay is not defined
overlay();
I need to access a method that is inside of requireJS in jquery.vegas. How can i do that?
require(["jquery"], function($) {
require(["files/jquery.vegas"], function(jQuery) {
set_overlay = true;
...
function overlay() {
$.vegas('overlay', {
src : 'overlays/10.png'
});
}
});
});
jquery.vegas
(function($) {
function loading() {
if (set_overlay == true) {
overlay();
}
}
})(jQuery);
In simple words, you can't access the function overlay since it is a closure function inside the annonymous function.
If the above code is in your control then I would suggest you to move the function overlay to a shared context between these two methods
ie
function overlay() {
$.vegas('overlay', {
src : 'overlays/10.png'
});
}
require(["jquery"], function($) {
require(["files/jquery.vegas"], function(jQuery) {
set_overlay = true;
...
});
});
(function($) {
function loading() {
if (set_overlay == true) {
overlay();
}
}
})(jQuery);
Before i ask this question, i never post about questions like this but I don't understand how to implement it in my code. i have code like this
window.onload = function() {
var url = getQueryVariable("url");
document.getElementById('view').src = url;
}
window.onload = function() {
var linkDirect = document.getElementsByClassName("frame");
for (var i = 0; i < linkDirect.length; i++) {
linkDirect[i].href = "http://namablog.blogspot.com/p/demo.html?url=" + linkDirect[i].href
}
}
then, how can I make the code execution using only one window.onload
You can use addEventListener or any jQuery equivalent.
window.addEventListener('load', function (){
alert('Function #1');
});
window.addEventListener('load', function (){
alert('Function #2');
});
Be sure to call these before the window is loaded.
window.addEventListener will not work in IE so use window.attachEvent
You can do something like this
function fun1(){
// do something
}
function fun2(){
// do something
}
var addFunctionOnWindowLoad = function(callback){
if(window.addEventListener){
window.addEventListener('load',callback,false);
}else{
window.attachEvent('onload',callback);
}
}
addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);
Just my 2 cents, My personal fav way of doing this is as follows:
function window_onload(cb) {
try {
if (typeof cb == 'function') {
if (document.readyState == 'complete') cb();
else if (window.hasOwnProperty('jQuery')) jQuery(window).on('load', cb);
else if (window['addEventListener']) document.addEventListener('load', cb, false);
else if (window['attachEvent']) {
// iFrame
if (window['frameElement']) document.attachEvent('onreadystatechange', function(){ if (document.readyState === 'complete') window_onload(cb); });
else window.attachEvent('onload', cb);
}
else {
var fn = window.onload; // very old browser, copy old onload
window.onload = function() { fn && fn(); ready(); };
}
}
}
catch (err) { if (window['console'] && console['error']) console.error("ERROR[window_onload()]", err); }
return window;
}
This pretty much covers just about everything. What little (mainly extremely old browsers I suppose?) it doesn't cover, you could easily debug, if needed. This also goes ahead and launches the callback if the document is already 'loaded'.
The simplest solution that has worked for me:
function doOnLoad() {
onloadfn1();
onloadfn2();
onloadfn3();
}
window.onload = doOnLoad;
This article has explained it in details: http://developer.expressionz.in/blogs/2009/03/07/calling-multiple-windows-onload-functions-in-javascript/
I hope this helps some of you.