(document).ready is a global scope? - javascript

Guys i have this function inside my script.js:
$(document).ready(function() {
function alert() {
alert('AAAAAAAA');
}
});
And i am trying to call here in my index.html:
$('.something').on('click', function() {
e.preventDefault();
alert();
});
But is showing my this error - alert is not defined.
But when i take off the document ready in the external script, the click handler will work. Why is that?
The document ready is creating a separate scope?

Using $(document).ready() creates a new function scope (note the function() after the .ready), so when you call
$(document).ready(function() {
function alert() {
alert('AAAAAAAA');
}
});
alert is only defined within the document.ready block. There are two ways to solve this issue:
Define the function outside of the document.ready block:
function customAlert() {
alert('AAAAAAAA');
}
Attach the function to the window object:
$(document).ready(function() {
window.customAlert = function() {
alert('AAAAAAAA');
};
});

Include the click event into the document.ready
Check it here http://jsfiddle.net/fbrcm45q/1/
$(document).ready(function() {
function showAlert() {
alert('AAAAAAAA');
}
$('.something').on('click', function(e) {
e.preventDefault();
showAlert();
});
});

First of all e.preventDefault is a function so you have to add braces at the end:
e.preventDefault()
Second alert is a function in javascrpt, so you need to rename your function to something else, for example:
$(document).ready(function() {
function special_alert() {
alert('AAAAAAAA');
}
});
and:
$('.something').on('click', function() {
e.preventDefault();
special_alert();
});

Related

How to call function inside ajaxComplete from document ready in jquery?

I want to execute function inside .ajaxComplete() from document ready.
$(function() {
$(document).on('click', '.woof_radio_label', function(e) {
if($(this).siblings('.woof_radio_term').is(':checked')) {
$('.page-secondary-content').removeClass('open');
$('.page-primary-content').removeClass('close');
$(this).siblings('.woof_radio_term_reset').click();
refineUrl();
} else {
$('.page-primary-content').addClass('close');
$('.page-secondary-content, .bottom-content').addClass('open');
}
});
});
$(document).ajaxComplete(function() {
function refineUrl() {
console.log('it works');
}
});
I am prompted with an error below:
Uncaught ReferenceError: refineUrl is not defined
at HTMLLabelElement. (scripts-custom.js?ver=4.9.7:15)
at HTMLDocument.dispatch (jquery.js?ver=1.12.4:3)
at HTMLDocument.r.handle (jquery.js?ver=1.12.4:3)
When I click the class woof_radio_label it will trigger an ajax event(Product Filter), I want to call a function on ajaxComplete().
Do you know how to do this?
You should declare function refineUrl() globally and then it can be called from anywhere. From ajaxComplete and from document.ready as well.
Like:
$(function () {
$(document).on('click', '.woof_radio_label', function (e) {
if ($(this).siblings('.woof_radio_term').is(':checked')) {
$('.page-secondary-content').removeClass('open');
$('.page-primary-content').removeClass('close');
$(this).siblings('.woof_radio_term_reset').click();
refineUrl();
} else {
$('.page-primary-content').addClass('close');
$('.page-secondary-content, .bottom-content').addClass('open');
}
});
});
$(document).ajaxComplete(function () {
//DO another stuff
});
function refineUrl() {
console.log('it works');
}
Declare your refineUrl() at the top of your script to prevent from such type of errors like,
function refineUrl() {
console.log('it works');
}
$(function(){
.....
});
$(document).ajaxComplete(function() {
refineUrl();
});

Reading a function from another function

The problem that when I click on .test it does not execute the do_alert(); function and gives me a error:
do_alert(); is not defined.
What's the problem? the main function helpers is already read when the page is loaded why can' get this function from logout_users function?
var setup_system = (function($) {
"use strict";
return {
init: function() {
this.logout_users();
this.helpers();
},
logout_users: function() {
$(document).on('click', '.test', function(e) {
e.preventDefault();
do_alert();
});
},
helpers: function() {
function do_alert() {
alert();
}
}
};
})(jQuery);
jQuery(document).ready(function() {
setup_system.init();
});
NOTE: I try to re-read the helpers function by adding this.helpers() inside logout_users function but nothing change.
It's because you've defined do_alert() within the scope of the helpers function.
To fix this you will need to move that function to within scope of the object you return. You could either put it at root level of the object (which would work fine, but could get messy if you have a lot of 'helper' functions) or you could nest it within your helpers property if you define that as another object. Personally, I'd use the latter to have some semblance of organisation. Try this:
var setup_system = (function($) {
"use strict";
return {
init: function() {
this.logout_users();
},
logout_users: function() {
var _obj = this;
$(document).on('click', '.test', function(e) {
e.preventDefault();
_obj.helpers.do_alert();
});
},
helpers: {
do_alert: function() {
alert('foo');
}
}
};
})(jQuery);
jQuery(function() {
setup_system.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Click me</div>
Note that I cached the reference to the object as _obj outside of the click handler, as within that block this will refer to the clicked .test element.
Do_alert function exist only in helpers method, so you can't access to it.
You need to declare your function directly in the logout_user method or outside, try this :
var setup_system = (function ($) {
"use strict";
return {
init: function () {
this.logout_users();
this.helpers();
},
logout_users: function() {
function do_alert(){
alert();
}
$(document).on('click', '.test', function(e){
e.preventDefault();
do_alert();
});
},
helpers: function () {
function do_alert(){
alert();
}
}
};
})(jQuery);
jQuery(document).ready(function () {
setup_system.init();
});
When helpers is invoked by the initfunction, all that is happening is that do_alert is being declared. But function declarations are hoisted to the top of their lexical scope. The lexical scope of do_alert is the scope defined by the helpers function. Therefore, do_alert is not accessible outside of helpers function.
A couple things you could do. The first one that comes to mind is: you could have the helpers method define a method called do_alert on the object being returned rather than merely declaring a function, like so:
helpers: function() {
this.doAlert = function() {
alert();
}
}
When your doAlert() is invoked by the event handler passed to jQuery, it will not work with the above solution. Instead you will need to make sure you call that doAlert on the returned object in that event handler. This is how you can do that:
logout_users: function() {
var self = this;
$(document).on('click', '.test', function(e) {
e.preventDefault();
self.doAlert();
});

How to call javascript function from ScriptManager.RegisterStartupScript?

I have the following javascript code:
<script type="text/javascript" language="javascript">
$(document).ready(
function () {
// THIS IS FOR HIDE ALL DETAILS ROW
$(".SUBDIV table tr:not(:first-child)").not("tr tr").hide();
$(".SUBDIV .btncolexp").click(function () {
$(this).closest('tr').next('tr').toggle();
//this is for change img of btncolexp button
if ($(this).attr('class').toString() == "btncolexp collapse") {
$(this).addClass('expand');
$(this).removeClass('collapse');
}
else {
$(this).removeClass('expand');
$(this).addClass('collapse');
}
});
function expand_all() {
$(this).closest('tr').next('tr').toggle();
};
});
</script>
I want to call expand_all function via code-behind .
I know I can use something like this, but it does not work and I don't understand used parameters:
ScriptManager.RegisterStartupScript(Me, GetType(String), "Error", "expand_all();", True)
Can you help me?
Because you have your expand_all function defined within anonymous $.ready event context. Put your code outside and it should work.
function expand_all(){
alert('test B');
}
$(document).ready(
function () {
// this won't work
function expand_all() {
alert('test A');
};
});
// will show test B
expand_all();
check this:
http://jsfiddle.net/jrrymg0g/
Your method expand_all only exists within the scope of the function inside $(document).ready(...), in order for you to call it from ScriptManager.RegisterStartupScript it needs to be at the window level, simply move that function outside the $(document).ready(...)
<script type="text/javascript" language="javascript">
$(document).ready(
function () {
....
});
function expand_all() {
$(this).closest('tr').next('tr').toggle();
};
</script>

Simplify code with named self invoking function

I have this script:
function fixHeight () {
$(".sidebar-mainbox-container").height($(window).height());
})
fixHeight();
$(window).on("resize", function() {
fixHeight();
})
I'm looking for a way to simplify it using a self invoking function and then call it in the resize event.
I've tried this one:
var fixHeight = (function () {
$(".sidebar-mainbox-container").height($(window).height());
})();
$(window).on("resize", function() {
fixHeight();
})
But in this way the value of the self-invoked function is assigned to fixHeight, and this can't work.
If I remove the self-invoking part...
var fixHeight = (function () {
$(".sidebar-mainbox-container").height($(window).height());
});
$(window).on("resize", function() {
fixHeight();
})
Then the function works only when I call it on resize, and this is not good.
How can I simplify this code to avoid 3 elements for such a simple task?
What's wrong with
$(window).on("resize", function() {
$(".sidebar-mainbox-container").height( $(this).height() );
});
?
To avoid an extra function call just trigger the event immediately after registering it.
$(window).on("resize", /* ... */).trigger("resize");

call function when click button

i have simply js file but i can't call function with parameter
the code
function removetr(str){
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(document).ready(function(){
$("input.buttonno1").click( removetr(1) );
});
the class of inputs that i want to remove it's values are g1,ga1 and gb1
i want to note that if i change the code to
function removetr(){
str=1;
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(document).ready(function(){
$("input.buttonno1").click( removetr );
});
it's work
You need to pass a function reference to an event handler, your current code is calling the function directly. Either build your function as an event handler, or pass an anonymous function reference to the click handler.
as event handler:
function removetr(e) {
var str;
str = e.data.str;
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(function () {
$("input.buttonno1").click({str: '1'}, removetr);
});
as anonymous function reference:
function removetr(str) {
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(function () {
$("input.buttonno1").click(function () {
removetr(1)
});
});

Categories