Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Friday, October 03, 2014

Dates in Javascript and the Underscore Framework

I haven't posted much as I've been busy.  I pan to post a few articles this month, just not sure when I will get to them.  In the meanwhile here is a good article on Javascript dates, which I have to deal with from time to time.

[Link]

Also a framework which might be useful is _underscore.js.  Looks like some useful cross-browser functionality.

[Link]

Thursday, April 24, 2014

Javascript GUIDs

It seems a lot of bright people have come up with Javascript implementations of GUIDs. The problem with them all seems to be the way Javascript handles both time and randomness. Also different browsers have their hang ups. Anyway, here is a solution that though not perfect has a good chance of generating SQL compliant GUIDs in Javascript with a very low (but not impossible) chance of collisions. Comments welcome.

 function generateUUID(){  
   var d = new Date().getTime();  
   var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {  
     var r = (d + Math.random()*16)%16 | 0;  
     d = Math.floor(d/16);  
     return (c=='x' ? r : (r&0x7|0x8)).toString(16);  
   });  
   return uuid;  
 };  

The above var d = new Date().getTime() can be improved by some modern Javascript features, but I'm not sure how supported they are. Here are some additional links with good information about Javascript GUIDs and problems with cryptography, randomness, and collisions.

http://slavik.meltser.info/the-efficient-way-to-create-guid-uuid-in-javascript-with-explanation/
http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
http://stackoverflow.com/questions/6906916/collisions-when-generating-uuids-in-javascript
http://af-design.com/blog/2008/09/05/updated-javascript-uuid-generator-v03/



Wednesday, March 05, 2014

Web Forms: Radio and Checkbox List Javascript Selection / Checked Manipulation

Yes, I know web forms aren't cool and all the hip kids are using MVC. Some of us are stuck enhancing existing applications (I don't want to call applications that bring in 100's of thousands of dollars "legacy").

Anyway, here is the scenario.  I've got a checkboxlist control.  I also have a radiobuttonlist with two entries, "All" and "None".  When I click on the radiobuttonlist I want to either check all the items in the checkboxlist control or uncheck all the items in the checkboxlist control.  I also wanted the checkboxlist control set so once individual items are checked the two options in the radiolistbuttonlist to be deselected / unchecked. I'm using Telerik controls so I can use a limited subset of jQuery, so I used it.

Step 1: Code Behind

On my page load I did this-

     ListItem lst1 = new ListItem ( Classes.Utility.Translate ( "AllLabel" ), "A" );  
     ListItem lst2 = new ListItem ( Classes.Utility.Translate ( "NoneLabel" ), "N" );  
     lst1.Attributes.Add ( "onclick", "SetClear(true)" );  
     lst2.Attributes.Add ( "onclick", "SetClear(false)" );  
     rdoOptions.Items.Add ( lst1 );  
     rdoOptions.Items.Add ( lst2 );  
     chkList.Attributes.Add ( "onclick", "return ClearRadioButtonList()" );  

The translate stuff don't worry about.  Just the way I do translation on the fly (for another post).  Note if you set the onclick event for each item or for all items by setting the onclick for the control rather than the items.

Step 2: Client Side

Here are a few Javascript functions I added-

  function ClearRadioButtonList() {  
     $("#<%= rdoOptions.ClientID %> input[type=radio]").prop('checked', false);  
    }  
    function SetClear(b) {  
     $("#<%= chkList.ClientID %> input[type=checkbox]").prop('checked', b);  
    }  

And it works!  I hope this helps someone.  These two pages were helpful to me figuring this out-

https://stackoverflow.com/questions/12482532/clear-radiobutton-list-selection-using-jquery
http://forums.asp.net/p/1303486/2549201.aspx


Friday, January 03, 2014

45 Useful Javascript Tips

Flippin' Awesome has compiled a list of 45 useful Javascript tips in one useful spot.  Well worth checking out.

[Link]

Friday, October 04, 2013

Free Online Javascript Book

I just started reading [this] book for free online about Javascript.  So far helpful.

Tuesday, September 03, 2013

JavaScript Scope and IIFEs

I ran into an issue I've never run into before.  I have some JavaScript files included in most pages on a website. These files define objects and populate them with properties like user options, site root URLs, an ajax callback function, etc...  Well there were a few pages that end up being pop ups on modals, and in that case one of the JavaScript objects wasn't getting created, so I was getting undefined errors.

Initially I created an immediately invoked function on the offending pages that I would pass the object into to make sure it existed and if not populate it.  However you cannot pass a variable or object to an IIF if it isn't defined.  The solution to the problem was simple, but I'd never done this before.  In any function you have access to the window object, which is where all the globals are kept, so you can actually declare global variables in functions without having to declare them outside a function first like I had been doing for years.



 (function () {  
       if (typeof window.SomeObj == 'undefined') {  
        window["SomeObj"] = {};  
        window["SomeObj"].property1 = 'blah blah';  
        window["SomeObj"].property2 = 'some option';  
       }  
 })();  


While I will probably circle back at one point an fix the scripts so that this little hack will not be needed, I thought it was cool you could do this and it had never occurred to me to try it.  Probably not a best practice, and most likely JavaScript 101 to those who develop JavaScript aps, but to me it was new and interesting.  I hope this technique helps someone else as well.

Update

For nested objects, this code snip might be of value as well http://jsfiddle.net/EGZxJ/ which came from http://joonhachu.blogspot.com/ though I haven't tested this yet.

Friday, May 20, 2011

Web Forms Bloat

When .Net web forms first came out I hated them. Then I got used to them. Now MVC is out, and if I would have skipped web forms I would have loved MVC I think, but because there are some great web form tools out there I find looking to doing something similar in MVC to be not worth it, at least at this point for me. But, web forms do have their draw backs. Look at the line number of this error...


Now I'm hoping this is a faulty line number, but unfortunately I don't think it is. MS Ajax -> Telerik generated Javascript handlers -> 200 lines of Javascript on a page with 5 web grids = a bazillion lines of code I guess.

I bet with MVC this would be about 1/20th of the line number...interesting.

By the way, here is how to do a global Javascript catch if debugging tools aren't working for you-

 window.onerror=function(m, u, ln){
       alert('Error: '+m+'\nURL: '+u+'\nLine: '+ln)
       return true
      }


More info here http://www.javascriptkit.com/

Sunday, February 20, 2011

Remembering Page Methods

Ok, I know ASP.Net web forms are all out of style now, even though if you are in a heavily data centric environment (one where you have grids upon grids upon grids) web forms still make the most sense in a lot of scenarios. So a lot of us are stuck with web forms and will be for as long as they are supported.

Anyway, one of the must under utilized capabilities in web form .Net apps are page methods. I sometimes forget the even exist in our jQuery / Ajax centered world. The preferred "best practice" method I'm sure would be to build a web service in WCF that you connect to through jQuery to do an Ajax call without a post back, but sometimes the quick and dirty approach that page methods offer is still useful.

So Zeeshan Umar has a good blog post about good old Page Methods here that the following code snip is based on.

http://zeeshanumardotnet.blogspot.com/2010/11/pagemethod-easier-and-faster-approach.html

I didn't add much to his example, so feel free to go right to his, but here is my own quick demo that I worked through just to remind myself that page methods still exists and how to use them based on Zeeshan's post.


The sample is just one aspx page with its code behind. This example demos submitting a registration form similar to what Zeeshan did-

The PageMethodsTest.aspx page (scroll bar at bottom, highlight all to copy/paste)



The PageMethodsTest.aspx.cs code behind.



Simple! Thanks for the reminder and quick code demo Zeeshan.

Bonus! Of course you can do all this with jQuery. One bonus using jQuery instead of Microsoft's ASP.Net AJAX is that you can leave the script manager off of your page. You can also easily call page methods ON OTHER PAGES (within the same project anyway), so then page methods really do become a poor man's quick and dirty alternative to WCF and ASMX for small task.

Here is an example HTML page that calls the above PageMethodTest.aspx RegUser method-

CallPageMethodsOnPageWJQuery.htm


Here is a useful blog post from Encosia for more info on jQuery / page method calls-

http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/


Thursday, February 17, 2011

JavaScript: Available Window Height and Width

Ok, here is another junior varsity tip for using Javascript to get the true available window height and width. Note I stole this code from somewhere (though I tweaked it). I'd give credit if I remembered where I got it from, I don't.

function HSAvailWidth() {
  if (typeof window.innerWidth != 'undefined')
    return window.innerWidth;
  if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth !== 0)
    return document.documentElement.clientWidth;
  return document.getElementsByTagName('body')[0].clientWidth;
}
function HSAvailHeight() {
  if (typeof window.innerHeight != 'undefined')
    return window.innerHeight;
  if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight !== 0)
    return document.documentElement.clientHeight;
  return document.getElementsByTagName('body')[0].clientHeight;
}



Or with jQuery...

$(window).height(); $(window).width();

Note: different browsers will have different available viewport height/widths because the browser tool bars very is size.


More here...

http://api.jquery.com/height/

Tuesday, February 15, 2011

Very Cool jQuery Sorting/Suffling Plugin called Isotope

Check this jQuery plugin called Isotope out.

http://isotope.metafizzy.co/

It has some pretty cool animation features, worth a look.

This Looks Interesting

A new Javascript/jQuery framework called the iX Framework looks pretty cool. It looks like it can do a lot (but not all) of what Telerik controls can do (though without the back end .Net integration). Might be work a look. $99 bucks for now.

http://www.intelligentexpert.net/


Friday, February 04, 2011

Quick Tip: Generate Unique ID's in Javascript

Here is a little code snippet I use to create unique id's in Javascript when I'm dynamically adding dom elements.

function HSCreateID(apd) {
  return apd + '' + new Date().getTime();
}

More on the Date().getTime() function in Javascript-

http://www.w3schools.com/jsref/jsref_getTime.asp


Saturday, August 21, 2010

JavaScript Tile Mapper

I can see all sorts of use for this Javascript Library. Use it for game maps, neighborhoods, etc...

http://polymaps.org/


Monday, July 26, 2010

8 Bit True Color Cycling in Javascript

Remember that retro 256k Ultima 4 esque bit animation? Well, it is back, and in the browser with out a plugin.

Direct link here-


Discussion here-


Worth the look. I can easily see how to use this in games.

Wednesday, April 21, 2010

Awesome Canvas 3D Demo

You look at this and think, cool. But really think about it. This proof of concept opens up a lot of possibilities.

Monday, April 05, 2010

Simple C# Wait Statement

I'm in a scenario where I'm making a get call to a web service, and if the get call fails for some reason I have to immediately call the web service back and let the client's know there is something up with their data. Well, apparently closing your web connection and then immediately calling it sometimes creates issues, as even though the service is closed, there is a little latency. So I was doing a thread.sleep before calling back, and that caused some issues. So here is a little wait statement equivalent I found

DateTime waitTime = DateTime.Now + TimeSpan.FromSeconds(2);
while (waitTime < DateTime.Now) {;}

Simple. Found it here - http://forums.xna.com/forums/p/908/6180.aspx