Basically my app work like that :
Index.php manage call to other pages.
Each page contains 2 function onLoad() and onClose() which are redefined in each page
Index.php call the pages and execute the onLoad
Basically, i preload the page in a hidden div, i execute the predefined $.onLoad function and the i put the loaded content into a visible div
My question is only about the onLoad() scope, i want to remove code from the jquery eval seq when i change page, but i need a way to define it in the page.php file without knowing the container
The eval/seq is probably the eval queue of jquery, can't found info about that, just obtain with firebug...
In 2 words, i would like to be able to remove injected dom and script when i change context (pages)
index.php
$.onLoad = function() {}
$("#blabla").onChange(function() {
$("#data_iframe").load(chaineUrl, {}, function(responseText, textStatus, XMLHttpRequest) {
$("#data_iframe").ready(function() {
$("#data_div").children().remove();
$.onLoad();
$("#data_iframe").children().hide().appendTo($("#data_div")).show(); $("#data_iframe").children().remove();
$.onLoad = undefined;
}
});
});
page.php
<script>
$.onClose = (function(){
$('#container').blablabla();
//alert("test");
});
$.onLoad = (function(){
$('#container').blablabla();
}
</script>
The problem is that the jquery EVAL/SEQ keep growing each time a page is opened
and there are some side-effect like calling multiple time a function...
I guess its a scope problem so can you help me correct my code
(i've try with or without the $ but doesn't change anything)
just for information
<div id="data_div"></div>
<div id="data_iframe"></div>
Thanks
I usually use $(document).ready instead of onload. No need to do the "onload" trigger in load complete function. The ready function within the page.php will do the same job.
And how about direct load into data_div?
index.php
$("#blabla").onChange(function() {
$("#data_div").load(page.php);
});
page.php
<script>
$(document).ready(function() {
$('#container').blablabla();
});
</script>
I didn't try page close function before, may be it is not what you want. But you can try:
<script>
$(document).ready(function() {
$('#container').blablabla();
$(window).unbind('unload');
$(window).unload(function(){
$('#container').blablabla();
//alert("test");
})
});
</script>
Related
I have Jquery function that executes AJAX query to server.
How can I call this after load page in the specified url page? May I bind this to element HTML, I mean:
<div id="graph" onload="function()"></div>
jQuery handles the HTML file with a variable called document.
Document has two popular event states
load when the page has been loaded
ready when the page has been loaded and all other decorations to the HTML have been applied.
jQuery provides hooks for these states.
To run javascript code after each of the events listed above, you have to put the function within the appropriate event scope.
For loading, this would be…
$(document).load(function() {
// javascript code you want to execute
})
After the page has been ready, but not yet rendered, you can apply some other javascript code using
$(document).ready(function() {
// javascript code you want to execute
})
One way using jQuery:
$(document).ready( function() {
//do whatever you need, you can check if some element exists and then, call your function
if($("#graph").length > 0)
callfunction();
});
No jQuery, only vanilla js:
window.onload = function() {
if(document.getElementById("graph"))
callfunction();
}
I have 2 external html pages loaded by this code:
<div id="header-div"></div>
<div id="footer-div"></div>
my js file contains this:
$(function () {
$("#header-div").load("/AfekDent/header.html");
$("#footer-div").load("/AfekDent/footer.html");
});
I want to run a function when specific element in the header file is created -
what trigger can i use for it?
It's ok the trigger will occur when all elements will be loaded.
thanks!
Add a callback to your load() call.
$(function () {
$("#header-div").load("/AfekDent/header.html", function() {
console.log('My header was loaded!');
});
});
You can use a callback on the #header-div, which will execute the code after the entire header has loaded.
$("#header-div").load("AfekDent/header.html", function() {
someFunction();
});
However, if you want to execute code after a specific element in the header loads, try something like:
$("#specific-element").on("load", function() {
someOtherFunction();
});
If you want to learn more about the difference between load and on("load"), look at this question or read the jQuery documentation for load and on().
For simplicity, I'd recommend executing code with $(document).ready(function() {yetAnotherFunction();});, but it depends on your specific case.
I am loading a webform and on this page I have an iFrame How can I delay the next line of my code from executing until the iFrame has completely loaded? I tried this javascript but it does not wait until the iFrame is totally rendered.
<script type="text/javascript">
document.getElementById('frame1').onload = function () {
}
EDIT
using the syntax below it writes the code to my window instead of actually executing it?
$( document ).ready(function() {
document.getElementById('frame1').onload = function () {
myWindow.close();
window.returnValue = true;
window.close();
}
});
Would it be possible to send a response to my client side C# code once the iFrame has fully loaded and I run my close() function from there?
You can use jQuery library
Wrap you function with this:
$( document ).ready(function() {
document.getElementById('frame1').onload = function () {
}
});
Don't forget to add jQuery library to your application. You can use the online one provided by Microsoft.
<head><script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script></head>
Strange situation:
I am building a menu bar using jQuery and CSS.
In my JavaScript file, I have an on-ready function like so:
$(document).ready(function(e) {
mark_active_menu();
}
and...
function mark_active_menu() {
var elementWidth = $("nav li").width();
alert(elementWidth);
}
For some reason, even BEFORE all the document finish loading, I'm getting the alert message with an incorrect width. Only when I release the message, the rest of the document loads and I'm getting the right width as it should be.
Why my function is being called BEFORE all the document finish loading?
Is there a way to load the function only AFTER a certain element done loading (Example: the nav element)?
You can use window.load, it will be triggered after all the resource have completed loading.
$(window).load(function(e) {
mark_active_menu();
});
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading, Reference
All the current solutions are just treating symptoms of the main problem. If you want your handler to execute after all your ajax loads, then you may use a promise.
var ajax1 = $.ajax();
var ajax2 = $.ajax();
jQuery(function($) {
$.when.apply($, [ajax1, ajax2]).done(function() {
// your code here
});
});
Try on the window load event :
$(window).load(function() {
//Stuff here
});
To be sure, Try window load
$(window).load(function(e) {
mark_active_menu();
}
Before(sometimes, doesn't load absolutely at the beginning, a few milliseconds after(0-200ms about)):
$(document).ready(function(){
$('body').hide(0);
});
After:
$(window).load(function(){
$('body').delay(500).show(0);
});
In my situation of work with AJAX and HTML. I have the same problem with functions $(document).ready() and $(window).load(). I solved this problem by adding handler of my event (that should work at HTML DOC), to the jQuery function that runs right after AJAX reguest was finished. Read this: "
jQuery.post()" (third parameter in the function).
In my code it looks like this:
var RequestRootFolderContent = function(){
$.post(
'PHP/IncludeFiles/FolderContent.inc.php',
function(data){
$('[class~="folder-content"]').html(data);
//Here what you need
$('[class~="file"]').dblclick(function(){
alert("Double click");
});
}
)
}
I've seen similar issues to this and answers but none seem to fix the issue.
I have a user control inside an update panel. Inside my user control I output javascript.
The javascript will not fire when triggered. If I move the javascript to the parent page outside of the usercontrol/updatepanels then it fires. This doesn't make sense to do this as I can't use this usercontrol on another page without either duplicating code...by either duplicating the entire javascript (different site) or adding references to a .js file in every page it's used on (same site). It's just less portable
I merely want to output the javascript with the control (inside the update panel).
The updatepanel is mentioned for accuracy of what I'm doing. It doesn't work even if I place the usercontrol outside of updatepanels.
Keeping it simple (This does not work for me):
USERCONTROL:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="_location.ascx.cs" Inherits="_location" %>
<script type="text/javascript">
function test() {
alert('Hello World!');
}
</script>
<a href="javascript:void(0);" onclick="javascript:test();">
Find For Me
</a>
PARENT:
<uc1:_location runat="server" ID="_location" />
Debugging in chrome tells me "Uncaught ReferenceError: test is not defined"
If I add the javascript directly to the onclick as below, it works:
onclick="alert('Hello World!');"
And as stated above, moving the function to the parent page ALSO works.
It's as if the browser ignores the script output from the user control.
Any ideas?
When you have an UpdatePanel and that UpdatePanel updates it's content, it treats it's content as simple text/html (not code), it does not have any parser available to run the script and make it available for the page.
So this content,
<script type="text/javascript">
function test() { alert('Hello World!'); }
</script>
<a href="javascript:void(0);" onclick="javascript:test();">
Find For Me
</a>
after client side code of update panel runs and updates content of the page, the script part is not parsed - its simple text/html for the page.
This part however runs
Find For Me
because the parse of the onclick attribute is done when you click on it.
There are following workarounds available:
Move your javascript into external file
Move you script outside of the UpdatePanel
Register the script in the code behind with RegisterClientScriptBlock or alternative functions.
In Addition to the solution that Adam Wood posted, I should say that you must use ScriptManager to register the script when using update panel, at least in .net 4.0 because otherwise it won´t work.
So you can put on the PageLoad event of the usercontrol:
string script = #" alert('this is a test');
alert('it worked')";
ScriptManager.RegisterStartupScript(Page,Page.GetType(),"scriptMelhoria",script,true);
Thanks to Aristos for sending me down the right path... Though his solution works, it did not answer the question of outputting the javascript from inside the usercontrol but instead suggested moving it outside. This was not the desired outcome, as stated, as it's not kept inside the control for easier portability.
Here is my solution that accomplishes this:
CS file:
String script = "<script type=\"text/javascript\">";
script += "function test() {";
script += "alert('Hello World!');";
script += "</script>";
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "locationScript", script);
One might use a stringbuilder if script is longer, but eitherway works.
This keeps the code entirely inside the usercontrol and it works from the onclick event of the a tag.
Try this;
You can find your script elements after udpdate panel callback and evaluate them.
Add a special attribute to your inline script tag to select elements after callback request.
<script type="text/javascript" data-tag='myscript'>
function test() {
alert('Hello World!');
}
</script>
And add this script to your update panel container aspx file.
<script>
if (Sys !== undefined) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(endPostbackRequest);
}
function endPostbackRequest(sender, args) {
$("script[data-tag='myscript']:not([data-run])").each(
function () {
eval.apply(window, [$(this).text()]);
$(this).attr('data-run', '1');
});
}
</script>
Preferred way of dealing with javscript code that is bound to DOM elements within UpdatePanel is to subscribe to endRequest event of PageRequestManager and execute your code here. For instance you want to set click event handlers here.
// that is standard way for asp.net to execute JS on page load
// pretty much the same as $(function(){ ...}) with jquery
function pageLoad() {
// find PRM instance and subscribe to endRequest
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
}
function endRequest() {
// set all handlers to DOM elements that are within UpdatePanel
$('<%= myButton.ClientID %>').on('click', test)
}
function test(e) {
alert('Hi')
}
Alternative solution will be to use event delegation like so:
function pageLoad() {
// delegate click event on .myButton inside .container
// to the .container DOM element
$('.container').on('click', '.myButton', test)
}
And have div with a class named container around your update panel. In this case your div.container is never removed from DOM so all event handlers on it will hold after partial postbacks.
Same code without jquery and using only asp.net ajax will look like this:
function pageLoad() {
Sys.UI.DomEvent.addHandler($("myContainer"), "click", delegatedTest);
}
function delegatedTest(e) {
// since asp.net ajax does not support event delegation
// you need to check target of the event to be the right button
if (e.target.id == "myButton") test(e)
}
function test(e) {
alert("HI")
}