How to call a JavaScript function on page load event? - javascript

I am calling a JavaScript function in a page to load an event as follows:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script12", "Disable();", true);
The Disable() function is:
function Disable() {
var ed = tinyMCE.activeEditor;
ed.getBody().setAttribute('contenteditable', false);
}
But, when my page loads, it is not working as intended.
Are there any obvious errors in my code?
Is my Disable() function implemented correctly?

You can use jQuery ready function.
Just include the reference of jQuery library (http://docs.jquery.com/Downloading_jQuery) in your page & call like this.
<script src="../jquery-1.7.1.min.js"></script>
<script>
$(function() {
Disable();
});
</script>

Related

How can I make this function execute automatically / on load [duplicate]

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)
<body onload="foo()">
When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.
Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.
If you want the onload method to take parameters, you can do something similar to this:
window.onload = function() {
yourFunction(param1, param2);
};
This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.
Another way to do this is by using event listeners, here's how you use them:
document.addEventListener("DOMContentLoaded", function() {
your_function(...);
});
Explanation:
DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...
function() Anonymous function, will be invoked when the event occurs.
Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply
The typical options is using the onload event:
<body onload="javascript:SomeFunction()">
....
You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.
<body>
...
<script type="text/javascript">
SomeFunction();
</script>
</body>
Another option is to use a JS framework which intrinsically does this:
// jQuery
$(document).ready( function () {
SomeFunction();
});
function yourfunction() { /* do stuff on page load */ }
window.onload = yourfunction;
Or with jQuery if you want:
$(function(){
yourfunction();
});
If you want to call more than one function on page load, take a look at this article for more information:
Using Multiple JavaScript Onload Functions
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
You have to call the function you want to be called on load (i.e., load of the document/page).
For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.
Try the code below:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
yourFunction();
});
function yourFunction(){
//some code
}
</script>
here's the trick (works everywhere):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use
let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });
// TEST: simulate element loading
let tmp=1;
function loadContent(name) {
setTimeout(()=>{
console.log(`Element ${name} loaded`)
content.innerHTML += `<div>My name is ${name}</div>`;
},1500*tmp++)
};
loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

Execute javascript after a partial postback of an updatepanel?

I have a page that add tree file script to it .
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/init.js"></script>
<script type="text/javascript" src="js/easing.js"></script>
I have a updatepanel with a dropdownlist. When run SelectedIndexChanged event (partial postback of an updatepanel), don't execute javascript .
Use the pageLoad function:
function pageLoad(sender, args) {
InitialiseSettings();
}
function InitialiseSettings(){
// replace your DOM Loaded settings here.
// If you already have document.ready event,
// just take the function part and replace here.
// Not with document.ready
$(element).slideUp(1000, method, callback});
$(element).slideUp({
duration: 1000,
easing: method,
complete: callback});
}
Or, try adding an "end request" event handler with .add_endRequest():
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InitialiseSettings)
Edit:
It would be a better idea for you to move your code from document.ready into InitialiseSettings(), and to then register it as a pageLoaded event handler.
Code Example
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitialiseSettings)
To run your javascript in full and partial postbacks, put your javascript code into javascript pageLoad() function.
function pageLoad()
{
//your javascript code
}
Example:
function pageLoad() {
$(':submit').click(function () {
CommodityArray();
});
$('#btn_image').click(function () {
CommodityArray();
});
$(".repHeader").disableSelection();
CommodityArray();
}
Hope it helps! :)
You have to use following code after your update panel.
<script type="text/javascript" language="javascript">
var pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
pageRequestManager.add_endRequest(NewCharacterCount);
</script>
where NewCharacterCount is your javascript function name.
Read this article Sys.WebForms.PageRequestManager endRequest Event
Hope it may help you.
If you are using UpdatePanel and you want to call a javascript function after content refresh in update panel, you can use below way to do it easily. In Page body tag , call a function RefreshContent()
<body onload="RefreshContent()">
<script type="text/javascript">
function RefreshContent()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
function EndRequestHandler()
{
alert("Add your logic here" );
}
</script>
Reference link
http://www.infoa2z.com/asp.net/how-to-call-javascript-function-after-an-updatepanel-asychronous-request-to-asp.net-page
You can use PageRequestManager client events. The sender parameter will contain the information you need. For example one could do this:
// Register event handler
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
/// Executed when all page content is refreshed, full page or async postback: https://msdn.microsoft.com/en-us/library/bb397523.aspx
function pageLoaded(sender, args) {
var isPostBack = sender.get_isInAsyncPostBack();
if(!isPostBack) return;
// PostBack logic here.
}

javascript placed inside an usercontrol loads but does not execute

inside a user control I have placed:
<script type="text/javascript">
$(function () {
alert("foooo");
};
</script>
This javascript loads into the browser fine, but does not executes. What is the proper way to add javascript code to a user control in ASP.NET MVC.
I have no experience with asp.net but the above is invalid JavaScript (no closing right parenthesis). Have you tried some very simple code like this:
<script type="text/javascript">
alert("foo");
</script>
You're missing a close paren at the end of your function. It should be like this:
});
Be sure that you have JQuery library referenced. Check it like with below code :
<script type="text/javascript">
if(JQuery == "undefined") {
alert("you didn't referenced the JQuery properly!")
}
$(function () {
alert("foooo");
});
</script>

How do I call a JavaScript function on page load?

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)
<body onload="foo()">
When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.
Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.
If you want the onload method to take parameters, you can do something similar to this:
window.onload = function() {
yourFunction(param1, param2);
};
This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.
Another way to do this is by using event listeners, here's how you use them:
document.addEventListener("DOMContentLoaded", function() {
your_function(...);
});
Explanation:
DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...
function() Anonymous function, will be invoked when the event occurs.
Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply
The typical options is using the onload event:
<body onload="javascript:SomeFunction()">
....
You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.
<body>
...
<script type="text/javascript">
SomeFunction();
</script>
</body>
Another option is to use a JS framework which intrinsically does this:
// jQuery
$(document).ready( function () {
SomeFunction();
});
function yourfunction() { /* do stuff on page load */ }
window.onload = yourfunction;
Or with jQuery if you want:
$(function(){
yourfunction();
});
If you want to call more than one function on page load, take a look at this article for more information:
Using Multiple JavaScript Onload Functions
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
You have to call the function you want to be called on load (i.e., load of the document/page).
For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.
Try the code below:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
yourFunction();
});
function yourFunction(){
//some code
}
</script>
here's the trick (works everywhere):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use
let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });
// TEST: simulate element loading
let tmp=1;
function loadContent(name) {
setTimeout(()=>{
console.log(`Element ${name} loaded`)
content.innerHTML += `<div>My name is ${name}</div>`;
},1500*tmp++)
};
loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

RadEditor and document.ready

document.ready is not working in RadEditor,
when i use the following jquery code
<script>
$(document).ready(function() {
$("#accordion").accordion();
});
</script>
It shows as error in RadEditor
The RadEditor control is a ASP.NET AJAX control and is initialized in the "init" event of the MS AJAX client framework. Try replacing the $(document).ready() code with the AJAX pageLoad() method:
<script type="text/javascript">
function pageLoad()
{
$("#accordion").accordion();
};
</script>
This way you can be certain that the accordion code will be executed after the editor is ready. Of course it depends on the code in your page, but with the given information, this seems the most probable issue.

Categories