Replacing body.onload in a user control - asp.net

I am refactoring a page that uses <body onload="myJS();"> to a user control. I understand I can do it using server side script registration on load.
If I want to do it on the client side (ascx), how would I do this?

Taken from http://snipplr.com/view/3116/cross-browser-add-event-listener/
// Cross-browser implementation of element.addEventListener()
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
Use it like this: addEvent(window, your_onload_handler). Or you could just use jquery for this and a lot of other things.

Romme's client-side approach is best. But just in case somebody wanted to know how to do it using server-side code in the ASCX file, stick this in at the top of your template:
<script runat="server">
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string strScript = "myJS();";
Page.ClientScript.RegisterStartupScript(this.GetType(), "OnLoadScript_" + this.ClientID, strScript, true);
}
</script>

OnLoad is generally a bad way to initialize JS, because it is only fired when all the resources have finished loading (including any images in the page).
The simplest, and most reliable way to call Javascript that you want to execute when the page finishes loading is to put an inline <script> block into the bottom of your HTML, right before the closing </body> tag:
<body>
... your page here ...
<script>myJS();</script>
</body>
</html>

Related

ClientScript.RegisterClientScriptBlock not working

I have a popup in my page which I am trying to show on dropdownlist selected index changed event.
Here is register statement
ClientScript.RegisterClientScriptBlock(GetType(),"id", "ShowApplicationPopUp()",true);
Here is my javascript function
function ShowApplicationPopUp() {
$('#NewCustomerMask').show("slow");
$('#NewCustomerApplicationPopUp').show("slow");
}
Both of my divs are initially hidden by using display:none; statement.
The problem is when my dropdownlist is changed the popup is not seen at all.I tried putting an alert statement to check if the function is called , and the alert statement is fired.Any ideas as to what I am doing wrong.
Any suggestions are welcome.
Thanks.
When you use RegisterClientScriptBlock the Javascript code is inserted early in the page, so it will run before the elements are loaded.
Use RegisterStartupScript instead, which places the code at the end of the form.
I too could not get this code to work but thanks to the above I now have working code. Note, I have a linkbutton inside an Ajax Update Panel.
in my code behind aspx.cs page is:
protected void OpenButton_Click(object s, EventArgs e)
{
// open new window
string httpLink = "../newWindow.aspx";
ScriptManager.RegisterStartupScript(this, GetType(), "script", "openWindow('" + httpLink + "');", true);
}
in my apsx page is first the link to jQuery source, then second the JavaScript for the openWindow function:
<script src="../js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
function openWindow(url) {
var w = window.open(url, '', 'width=1000,height=1000,toolbar=0,status=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1');
w.focus();
}
</script>
and the link that makes it all happen:
<asp:LinkButton Text="Open New Window" ID="LnkBtn" OnClick="OpenButton_Click" runat="server" EnableViewState="False" BorderStyle="None"></asp:LinkButton>
Im not a jQuery expert and must attribute some of this to the following blog:
https://blog.yaplex.com/asp-net/open-new-window-from-code-behind-in-asp-net/

Start javascript from asp.net page

Hi I have a usercontrol which includes some JavaScript, if I add the control to a standard web page I can start the JavaScript in the body tag, like this
<body onLoad="Start()">
The problem is that I need to add the control to a webpage which is inside a masterpage, how do I then start the script when a page inside a masterpage doesn't have a body tag.
You can register it using:
Page.ClientScript.RegisterStartupScript()
For your case, it would be this:
Page.ClientScript.RegisterStartupScript(GetType(), "MyScript", "Start()", true);
Include jQuery and put your initialization code inside $(document).ready().
If you want to strictly use .NET functionality, and your page is properly marked up with runat="server", you could use Page.ClientScript.RegisterStartupScript() as well.
You can change the body tag to runat server and give it an id.
<body id="masterBody" runat="server">
Then on page load:
public void Page_Load(Object sender, EventArgs e)
{
HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("masterBody");
body.Attributes.Add("onload", "Start()");
}
Try binding to the DOM document.ready event to load your content after the document has completed rendering

ASP.NET navigate to anchor in code behind

I have a simple Web Form with code like this:
//...
//tons of text
//...
<a name="message" />
//...
//tons of text
//...
<asp:Button ID="ButtonSend"
runat="server"
text="Send"
onclick="ButtonSend_Click" />
After POST I want to navigate user to my anchor "message". I have following code for this:
protected void ButtonSend_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterStartupScript(this.GetType(),
"navigate",
"window.location.hash='#message';",
true);
}
This simple JavaScript is not working in Firefox 3.5.2 - url is changing in browser but page is not navigated to anchor. In IE 8 it works perfectly.
Why this JavaScript code is not working in Firefox? Am I missing something?
I've solved my problem. JavaScript code was called before my anchor even existed. That's why Firefox wasn't scroll page down.
My code looks now like tihs:
this.ClientScript.RegisterStartupScript(this.GetType(),
"navigate",
"window.onload = function() {window.location.hash='#message';}",
true);
After page load I'm calling my simple JavaScript function.
The key to found solution was Cleiton answer. Firebug reports that getElementById was returning null reference. Then I looked at generated HTML like andrewWinn suggested - JavaScript was called before anchor existed. Made little googling and found solution.
Thanks for your answers!
Mendoza, you can use native scrollIntoView function.
To do what you want, just write:
this.ClientScript.RegisterStartupScript(this.GetType(),
"navigate",
"document.getElementById('id_of_the_element').scrollIntoView();",
true);
I ran into this once. Have you taken a look at the actual HTML? If I remember, FireFox was being case sensative on the anchors. I don't know if that changed recently or not.
You could try using the jQuery LocalScroll plugin. Using this, you could scroll using:
$(function() {
$.scrollTo("#message");
});
Or with your ASP.NET code:
protected void ButtonSend_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterStartupScript(this.GetType(),
"navigate",
"$(function() { $.scrollTo('#message'); });",
true);
}
It's not an ideal solution, especially if you're not using jQuery anywhere in your project already, but it might solve your problem.

Javascript to access control in MasterPage

I have a textbox control Super1 in my MasterPage.
I am using javascript to access this control from my content page like this:
<asp:Content ID="ContentPage" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function Somethin() {
{
document.forms[0].elements['Super1'].value = "sdfsd";
//document.getElementById('<%=Super1.ClientID%>').value = "sdfsdf";
}
}
</script>
</asp:Content>
But while page load it says Super1 not found. How can I access Super1?
In your masterpage's onload add this code :
string script = #"<script>
function Somethin() {
document.getElementById('" + Super1.ClientID + #"').value = 'sdfsd';
}
Somethin();
</script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered("somethin_script_block"))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "somethin_script_block", script);
}
this will add your script to the end of the page.
EDIT : I just realized, you use your controls ID directly in your javascript code. this may cause the exception. I update your code to fix it.
I hope this helps.
You have to make sure the document has loaded, make sure to call your functions that rely on the DOM being loaded onload. E.g.:
<script type="text/javascript">
window.onload = function() {
Somethin();
}
</script>
From the sample code you posted and since you said you are using a control, check the rendered id of the control you are trying to get at. In my experience the name is something crazy like ctl100_masterpagename_namingcontainer_controlname... that needs to show up in the js as well.
Super1 might be in a different naming container (the masterpage's control collection). You either need to render out the clientid of the control in a global javascript variable during the masterpage rendering so it can be accessed by javascript in the child page or you need to get a reference to the Masterpage, find the control there and write out the client Id in your child pages javascript...
Something like...
if the text box is in its own content place holder
var txtSuper1 = Master.FindControl("ContentPlaceHolderName").FindControl("Super1") as Textbox;
or if its not in a content place holder
var txtSuper1 = Master.FindControl("Super1") as Textbox;
3rd option might be to expose the control as a property of the masterpage (not sure) - my webforms is rusty.
On the master page, declare a javascript variable for the control, e.g:
<asp:TextBox id="Super1" runat="server"/>
...
<script type="text/javascript">
var txtSuper1 = document.getElementById('<%= Super1.ClientID %>');
</script>
It's important that you use the ClientID property, because the rendered control's ID (on the client) will be different from the server control's ID (due to naming containers).
Now you can access the textbox from javascript declared in the content pages:
<asp:Content ID="ContentPage" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function Somethin()
{
txtSuper1.value = "sdfsd";
}
</script>
click me
</asp:Content>
BTW: in your code there are duplicate curly-braces in function Somethin() {{ ... }}

ASP.NET WebForms + Postback then open popup

I have a LinkButton that has to postback to perform some logic.
Once it is finished, instead of loading the page back up in the browser, I want to leave it alone and pop open a new window.
So far, the best idea I've had is to put the LinkButton in an UpdatePanel, and have it render some JavaScript out when it reloads, yet I think that is totally hacky. Also, if I recall right, JavaScript within a update panel won't run anyways.
Any other ideas?
Use LinkButton.PostBackUrl to set a different page to POST to, and some client script to get a new window (and the old target restored so that future postbacks work normally). The 2nd page can use PreviousPage to get access to any needed state from the original page.
<script runat="server">
void lnk_Click(object sender, EventArgs e) {
// Do work
}
</script>
<script type="text/javascript">
var oldTarget, oldAction;
function newWindowClick(target) {
var form = document.forms[0];
oldTarget = form.target;
oldAction = form.action;
form.target = target;
window.setTimeout(
"document.forms[0].target=oldTarget;"
+ "document.forms[0].action=oldAction;",
200
);
}
</script>
<asp:LinkButton runat="server" PostBackUrl="Details.aspx" Text="Click Me"
OnClick="lnk_Click"
OnClientClick="newWindowClick('details');" />
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
// Do some server side work
string script = "window.open('http://www.yahoo.com','Yahoo')";
if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"NewWindow",script, true);
}
}
One thing you could try is to have your LinkButton OnClick event do its processing, then register a Page.ClientScript.RegisterStartupScript with the popup code, which will put some Javascript into the tag to fire off after the page loads. This should launch your new window after the processing completes.
EDIT: Reading your comment, I believe you can still use this approach, have your results stored in a session variable, and then have the popup page pull the results from there.

Resources