Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, April 13, 2010

Javascript OnLoad Page Resize and Move to Center

Here's a snippet for loading a web page with set width and height and moving it at the center of the screen.


window.onload = function() {
    var width = 800;
    var height = 600;
    window.resizeTo(width, height);
    window.moveTo(((screen.width - width) / 2), ((screen.height - height) / 2));
}


For this sample we resize the window to 800 by 600 and then placed it at the center of the screen by taking the screen width and height (current monitor resolution) then subtracting it with the set width and height (800 and 600 respectively) and finally diving it by 2. Now, simply place this script on the head part of the page and that's it.

Tuesday, April 6, 2010

Disable Refresh in Webpage Using Javascript (F5 & Ctrl + R)

Okay here's another script for disabling refresh (F5 & Ctrl + R) in your web pages.


document.onkeydown = function() {    
    switch (event.keyCode) { 
        case 116 : //F5 button
            event.returnValue = false;
            event.keyCode = 0;
            return false; 
        case 82 : //R button
            if (event.ctrlKey) { 
                event.returnValue = false; 
                event.keyCode = 0;  
                return false; 
            } 
    }
}

Same as before, you can add this to your main javascript file and place it in the head part of your page.

It works by adding a function to your page's onkeydown event. Then we simply get which button was pressed by using event.Keycode (116 for F5 and 82 for R). Also, notice the "if" statement for R, it simply checks if the control button was pressed at the same time as R by checking event.ctrlKey. 

But there's a limitation to handling page refreshes with this code. You simply cannot control the refresh button specific to your browsers' toolbar. 



So the only way to really prevent users to refresh the page is by using this code and at the same time opening your page at a new window without the toolbar. 

Check http://codingresource.blogspot.com/2010/01/javascript-windowopen-in-net.html for more info on how to do that.

Disable Right-Click in Webpage Using Javascript

Here's a simple javascript snippet you can use to disable right-click in your web pages:



document.oncontextmenu = function() { 
    alert('Right-click is disabled.');
    return false; 
}


Just place the above code anywhere in your main javascript file or in the head part of the main page. You can also remove or change the alert if you don't want to notify the user.

Thursday, March 4, 2010

AutoCompleteExtender problems with ModalPopupExtender

If you've tried to use the AutoCompleteExtender inside a ModalPopupExtender, you'll notice that the autocomplete options show behind the modal popup. This is a Z-index problem in which the ModalPopupExtender overrides all other controls. If you check the modal's Z-index you'll see that it uses 100001 for its foreground element, so use something higher like 10000001.

<cc1:AutoCompleteExtender ID="ace" runat="server" OnClientShown="ShowOptions">
</cc1:AutoCompleteExtender>

<script language="javascript" type="text/javascript">
    function ShowOptions(control, args) {
        control._completionListElement.style.zIndex = 10000001;
    }
</script>
 
So we use the OnClientShown property which will call a javascript function to change the AutoCompleteExtender's Z-index when it kicks in.

Thursday, February 25, 2010

ASP.NET C# OnEnter event in TextBox

Here is a workaround for ASP.NET C# if you want an event that triggers on pressing the "Enter" key on your keyboard while still inside a textbox.


First the javascript snippet:



if (event.which || event.keyCode) {
    if ((event.which == 13) || (event.keyCode == 13)) {
        document.getElementById('btnClick').click();
        return false;
    }
} 
else {
    return true;
};


It just captures the "Enter" key press (which is 13) and then clicks the corresponding button to trigger its event. So you just place this script on the textbox's onkeydown attribute which I'll show in just a sec.


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        txtBox.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnClick.UniqueID + "').click();return false;}} else {return true}; ");
    }
}


Just add the attribute on the Page_Load event and you're done.

Check this link for more keycodes: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx

-k

Thursday, February 11, 2010

Get Client MAC Address & IP Address using Javascript

This is somewhat similar to the previous post Get client cpu id with javascript, so the client still needs to enable ActiveX components on his browser. Read more on the said post for details.

Ok if you're done reading, you'll notice we simply change the script to this:

<script type="text/javascript">
    var macAddress = "";
    var ipAddress = "";
    var computerName = "";
    var wmi = GetObject("winmgmts:{impersonationLevel=impersonate}");
    e = new Enumerator(wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True"));
    for(; !e.atEnd(); e.moveNext()) {
        var s = e.item();
        macAddress = s.MACAddress;
        ipAddress = s.IPAddress(0);
        computerName = s.DNSHostName;
    }
</script>

Instead of Win32_Processor, here we'll access Win32_NetworkAdapterConfiguration to read network related details like the MAC Address, IP Address and the computer name.

Then we can simply use textboxes to display that information or whatever you like.

<input type="text" id="txtMACAdress" />
<input type="text" id="txtIPAdress" />
<input type="text" id="txtComputerName" />

<script type="text/javascript">
    document.getElementById("txtMACAdress").value = unescape(macAddress);
    document.getElementById("txtIPAdress").value = unescape(ipAddress);
    document.getElementById("txtComputerName").value = unescape(computerName);
</script>

And just like before, make sure to place the declarations snippet above this script for it to display the values properly. Now the client can see his/her own MAC and IP Addresses.

Read more about the Win32_NetworkAdapterConfiguration object here http://msdn.microsoft.com/en-us/library/aa394217(VS.85).aspx


-k

Wednesday, February 10, 2010

ASP.NET AJAX this._form is null error on javascript

If ever you encounter this sneaky error on your ASP.NET AJAX-Enabled websites (you would know it when you see the this._form is null javascript error message or simply if your controls don't cause postbacks anymore) the culprit is the javascript declaration found on the head tag in the html page.


If you have declared it like this:


<script src="scripts/main.js" type="text/javascript" />


Simply change it to this:


<script src="scripts/main.js" type="text/javascript"></script>


And problem is solved.




-k

Sunday, January 31, 2010

ASP.NET Server tag was not well formed

TIP: ASP.NET C# Expression Language with Javascript

Here's a tip on how to use C# bind code inline with javascript events, first let's use a LinkButton for example:

<asp:LinkButton ID="lnkBtn" runat="server" OnClick="lnkBtn_Click" OnClientClick='<%# "document.getElementById(\"txtHtmlText\").value = " + Eval("id") + ";" %>' />

Imagine this LinkButton is inside a binded control like Gridview or Repeater, etc., now look at the OnClientClick attribute. Remember to be careful with single and double quotes.

1. Use single quotes to contain the whole expresion.

          OnClientClick='  ...  '

2. Enclose inner javascript statements with double quotes and concatenate it with .NET bind statements (like Eval()) with the "+" symbol. 

          "document.getElementById(\"txtHtmlText\").value = " + Eval("id") + ";"

3. Use escaped double quotes (the one with the slash) if ever you'll use double quotes inside another one.

          getElementById(\"txtHtmlText\")

So the next time you get the error "Server tag was not well formed" just remember these 3 tips.



-k

Thursday, January 28, 2010

ASP.NET C# Refresh page from code behind

To refresh your page you may use the javascript function:


window.location.reload();


For example you can use that on the OnClientClick attribute of an ASP.NET button:


<asp:button ID="btnRefresh" OnClick="btnRefresh_Click" runat="server" Text="REFRESH" 
OnClientClick="window.location.reload();" />


The code above will work fine, but if let's say you have some other server-side logic you want to run on the code for btnRefresh_Click, it won't be executed because the page would already be refreshed by then.


So to run your server-side code, first remove the OnClientClick attribute on the asp button tag above. Then place the following code inside your button click event:



protected void btnRefresh_Click(object sender, EventArgs e)
{
    //Your logic here...
    Page.Response.Redirect(HttpContext.Current.Request.Url.ToString(), true);
}


We simply redirect the page to its current url and that does the trick.



-k





Wednesday, January 27, 2010

Javascript Window.Open() in .NET

Here's an example on how to popup a new window using javascript in .NET. First we'll use a simple button as the trigger source for the popup.

<asp:Button ID="btnPopup" runat="server" />

Then on the page load in the code behind, add an onclick attribute to the button.

protected void Page_Load(object sender, EventArgs e)
{
    btnPopup.Attributes.Add("onclick", "window.open('http://" + Page.Request.Url.Authority + "/TestPage.aspx','Test','status,toolbar,location,menubar,directories,resizable,scrollbars,width=400,height=400')");
}
 
The Page.Request.Url.Authority in the code above will retrieve the root url of your site. Then just add the name of the aspx file to popup after the forward slash (if it is within another directory, just add the directory name before the aspx file, and so forth).
 
To explain the javascript part, window.open() accepts 3 parameters: the url of the site to popup, the window name (not title, the title should be in the head part of the new page, so make sure it doesn't have spaces), and window features.
 
Here's some of the commonly used window features:
 
status:
 

   
toolbar:


 
location:


 
menubar:


 
directories:


 
resizable: window can be resized


 
scrollbars:


 
width: the width of the window in pixels
 
height: the height of the window in pixels



To use these features simply add them to the list like this:

"window.open
('http://www.testpage.com','Test','status,toolbar,location,menubar,directories,resizable,scrollbars,width=400,height=400')"




If not then simply omit them:

"window.open('http://www.testpage.com','Test','width=400,height=400')"





That's it, one note though, make sure that the aspx page in the url exists or you'll get an error.



-k

Thursday, January 21, 2010

Get Client CPU ID with Javascript

For whatever purpose it may serve, here's how to get the client CPU ID through javascript. Just a warning though, this script uses ActiveX object which is disabled by default on browsers and I'm not sure if you can enable it on non-IE. So for now we'll just do it with Internet Explorer.


Go to Tools then Internet Options.





Then on the Security tab click on "Custom Level..."





Go down until you see "Initialize and script ActiveX controls not marked as safe..." and enable it then click Ok.


Now we go to the scripting part. Add this next snippet in your html page.



<script type="text/javascript">
    var str = "";
    var wmi = GetObject("winmgmts:{impersonationLevel=impersonate}");
    e = new Enumerator(wmi.InstancesOf("Win32_Processor"));
    for(; !e.atEnd(); e.moveNext()) {
        var s = e.item();
        str = s.ProcessorID;
    }
</script>


You can add the script above anywhere on your html head or body, but if you chose to put it on the body be sure to place it anywhere above this next snippet, which just displays the CPU ID in the page.


<b>Client CPU ID : </b><span id="spanCPUID" />

<script type="text/javascript">

    document.getElementById("spanCPUID").innerHTML = str;
</script>
                        


And that's it, you should now see the client computer's cpu id when you run the page.


-k