The aim is to increase cyber and internet security awareness among surfers. Google and others are joining the move. So I thought I would write a post regarding internet security to add my 2 cents. In this post you will find JavaScript function that generates random passwords of any length as well as jQuery version.
JavaScript Password Generator
$.extend({
password: function (length, special) {
var iteration = 0;
var password = "";
var randomNumber;
if(special == undefined){
var special = false;
}
while(iteration < length){
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if(!special){
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
}
iteration++;
password += String.fromCharCode(randomNumber);
}
return password;
}
});This function takes two parameters: integer value for password length and optional boolean value true if you want to include special characters in your generated passwords.
Examples of generated passwords
password(8);
// Outputs: Yrc7TxX3
password(12, true);
//Outputs: C}4_ege!P&#MjQuery password generator
$.extend({
password: function (length, special) {
var iteration = 0;
var password = "";
var randomNumber;
if(special == undefined){
var special = false;
}
while(iteration < length){
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if(!special){
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
}
iteration++;
password += String.fromCharCode(randomNumber);
}
return password;
}
});
// How to use
$.password(8);
$.password(12, true);If you have better solution, just tell me !
Get URL parameters & Using jQuery
In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient.
Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by Roshambo that does just that.
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}The function returns an array/object with your URL parameters and their values. For example, consider we have the following URL:
http://www.example.com/?me=myValue&name2=SomeOtherValueCalling getUrlVars() function would return you the following array:
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}To get a value of first parameter you would do this:
var first = getUrlVars()["me"];
// To get the second parameter
var second = getUrlVars()["name2"];To make the script syntax to look more jQuery like syntax I rewrote it as an extension for jQuery:
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});Now you can use it in the following way:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its nam
var byName = $.getUrlVar('name');If you have better solution, just tell me !
Select Options Sorting and dropdown Using jQuery
There are probably a dozen ways to skin this cat, but this is how I did it (I was already using jQuery on this site):
// get the select
var $dd = $('#select-id');
if ($dd.length > 0) { // make sure we found the select we were looking for
// save the selected value
var selectedVal = $dd.val();
// get the options and loop through them
var $options = $('option', $dd);
var arrVals = [];
$options.each(function(){
// push each option value and text into an array
arrVals.push({
val: $(this).val(),
text: $(this).text()
});
});
// sort the array by the value (change val to text to sort by text instead)
arrVals.sort(function(a, b){
return a.val - b.val;
});
// loop through the sorted array and set the text/values to the options
for (var i = 0, l = arrVals.length; i < l; i++) {
$($options[i]).val(arrVals[i].val).text(arrVals[i].text);
}
// set the selected value back
$dd.val(selectedVal);
}The above code will only work if the option values are numbers. If the values are alphanumeric and we are doing an alphabetical sort, then the sort function should be replaced with:
arrVals.sort(function(a, b){
if(a.val>b.val){
return 1;
}
else if (a.val==b.val){
return 0;
}
else {
return -1;
}
});If you have better solution, just tell me !
JQuery and JSON Web Service
Use JQuery to consume JSON Web Services is a lightweight method, for increment performance in your website.
If you want call a JSON Web Service from your javascript code, you should : use HTTP POST and content-type "application/json; charset=utf-8″. Asp.Net Ajax make this for you transparently.
$(document).loadMyContent(function() {
$.ajax({
type: "POST",
url: "myService.asmx/GetMyContent",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#myDiv').html(msg.d);
}
});
});Insert javascript code after content for best performance.
JQuery Pluggins
JQuery Pluggins is a mechanism for adding in methods and functionality. You can found a lot of available pluggins. Read more about pluggin developing.
A simple example :
Using our developped pluggin : $("div p").mypluggin ();jQuery.fn.mypluggin = function() {
return this.each(function(){
alert(this);
});
};Combining javascript file
howto combine javascript files in 3.5 and 4.0.
<asp:ScriptManager runat="server">
<CompositeScript>
<Scripts>
<asp:ScriptReference Name="WebForms.js" Assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<asp:ScriptReference Name="MicrosoftAjaxWebForms.js" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<asp:ScriptReference Name="MicrosoftAjax.js" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</Scripts>
</CompositeScript>
</asp:ScriptManager>In 4.0 <asp:ScriptManager runat="server" EnableCdn="true"/>
If you have better solution, just tell me !
Ajax Autocomplete textbox add progress Image using javascript
In this example i m going to describe how to add animated Progress Image inside Ajax Auto complete extender textbox to represent loading of data.
For achieving this functionality i am using two different approaches for different versions of AjaxControlToolkit.dll
1st ApproachThis approach is very simple and can be handy if you are using older/earlier version of AjaxControlToolkit (eg versions like 1.0.10201.0) which does not support css properties or properties like onclientpopulating. For this write the below mentioned javascript in head section of html markup of the aspx page.
<script type="text/javascript">
function ShowImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'url(images/loader.gif)';
document.getElementById('txtAutoComplete')
.style.backgroundRepeat= 'no-repeat';
document.getElementById('txtAutoComplete')
.style.backgroundPosition = 'right';
}
function HideImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'none';
}
</script>In this script I've written two function to show and hide image, in the functions i m setting the background image style using document.getElementByID method , Now write this code in Page_Load event of aspx page.
protected void Page_Load(object sender, EventArgs e)
{
this.txtAutoComplete.Attributes.Add
("onkeypress", "ShowImage()");
this.txtAutoComplete.Attributes.Add
("onblur", "HideImage()");
}Here i've added onblur and onkeypress attributes to textbox and calling respective function of javascript to show hide image.Build the solution and run ti see the results.
2nd approach
This approach works if you are using newer versions of AjaxControlToolkit.dll (Version 1.0.20229.20821 or later)
For this write the above mentioned javascript in head section of html markup of page.
Now in source of autocomplete extender add onclientpopulating="ShowImage" and onclientpopulated="HideImage".
<ajaxToolkit:AutoCompleteExtender runat="server"
ID="AutoComplete1"
BehaviorID="autoComplete"
TargetControlID="txtAutoComplete"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12"
CompletionListCssClass=
"autocomplete_completionListElement"
CompletionListItemCssClass=
"autocomplete_listItem"
CompletionListHighlightedItemCssClass=
"autocomplete_highlightedListItem"
onclientpopulating="ShowImage"
onclientpopulated="HideImage">
</ajaxToolkit:AutoCompleteExtender>Complete html source of the page look like
<head runat="server">
<title>Progress Image in AutoComplete TextBox
</title>
<script type="text/javascript">
function ShowImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'url(images/loader.gif)';
document.getElementById('txtAutoComplete')
.style.backgroundRepeat= 'no-repeat';
document.getElementById('txtAutoComplete')
.style.backgroundPosition = 'right';
}
function HideImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'none';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
<br />
<div>
<asp:TextBox ID="txtAutoComplete" runat="server" Width="252px">
</asp:TextBox><br />
<ajaxToolkit:AutoCompleteExtender runat="server"
ID="AutoComplete1"
BehaviorID="autoComplete"
TargetControlID="txtAutoComplete"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12"
CompletionListCssClass=
"autocomplete_completionListElement"
CompletionListItemCssClass=
"autocomplete_listItem"
CompletionListHighlightedItemCssClass=
"autocomplete_highlightedListItem"
onclientpopulating="ShowImage"
onclientpopulated="HideImage">
</ajaxToolkit:AutoCompleteExtender>
</div>
</form>If you have better solution, just tell me !
jQuery AJAX functions (load(), $.get(), etc.) are not loading new page versions problem
Today I would like to share with you a quick solution to the common problem when your AJAX calls to some page that changes over time is not being loaded to your page. In other words, jQuery or your browser is not loading new version of the page.
This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I believe, do not experience this problem. Usually it occurs when you use jQuery AJAX functions in javascript setInterval() method. Basically, what happens is that Firefox can not see the changes been made to the page and thinks it’s the same with the old one. So Firefox loads it from cache and you don’t see the new version of your page. To resolve this issue, you should simply add a random string to the request like below.
The solution:
// Reload mypage.html every 5 seconds
var refresh = setInterval(function()
{
// Minimized code, suggested by Kovacs
$('#mydiv').load("mypage.htm?" + 1*new Date() );
}, 5000);If you have better solution, just tell me !
Javascript for() loop vs jQuery .each() performance comparison
This post is an outcome of 15 minutes of free time and a question that I had yesterday. This question were:
How fast jQuery’s .each() method is?
How does it compare to javascript’s native for loop?
It is clear without any performance tests that native javascript for loop is faster, but I always used jQuery’s .each() utility with caution. It always felt like I will get a performance penalty for using it. So I tried to never use it.So today, I wrote up a little javascript performance test and got my answers. Basically, I created an array and iterated through it using native for loop and jQuery’s .each() iterator. All I did was just an iteration and no array amendments or any other logic. I know it is very basic, but that’s exactly what I want to know. How fast they iterate!
Performance test code:
console.time('TestNative');
for( i=0; i < myArray.length; i++){
myArray[i];
}
console.timeEnd('TestNative');
console.time('TestjQuery');
jQuery.each(myArray, function(i, val) {
val;
});
console.timeEnd('TestjQuery');Performance test results:
JavaScript Native FOR loop
Array size Time
========== ======
10,000 7ms
100,000 62ms
1,000,000 613ms
jQuery .each() loop
Array size Time
========== ======
10,000 10ms
100,000 177ms
1,000,000 1100msUsually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.
Dynamically adding table row count number using JavaScript and jQuery
Recently on jQuery mailing list a user asked how he/she could add a row count in their table automatically. So I wrote a code snippet which looks like this:
$(document).ready(function(){
$("table").each(function(){
if($(this).is('table')){
$('thead th:first-child, thead td:first-child', this).each(function(){
if($(this).is('td'))
$(this).before('<td>#</td>');
else if($(this).is('th'))
$(this).before('<th>#</th>');
});
$('tbody td:first-child', this).each(function(i){
$(this).before('<td>'+(i+1)+'</td>');
});
}
});
});This code was for specific case, where there is only one table on the page and it has only one row in its header. That is why I took into the account the possibility of row spans and multi line rows in header and rewrote the code. Then made a plugin out of it. So, here is the final code:
function($){
$.fn.extend({
addCount: function() {
return $(this).each(function(){
if($(this).is('table')){
$('thead th:first, thead td:first', this).each(function(){
if($(this).is('td'))
$(this).before('<td rowspan="'+$('thead tr').length+'">#</td>');
else if($(this).is('th'))
$(this).before('<th rowspan="'+$('thead tr').length+'">#</th>');
});
$('tbody td:first-child', this).each(function(i){
$(this).before('<td>'+(i+1)+'</td>');
});
}
});
}
});
})(jQuery);To apply it to your tables use this code:
$('table').addCount();
$('.some-table-class').addCount();
$('#some-table-id').addCount();If you have better solution, just tell me !
QR Code (generator) plugin for jQuery & JavaScript
I recently came across a 2 dimensional barcode called QR Code. QR code’s are popular in Japan and they are mainly used there to quickly get to some website on their mobiles by simply taking a picture of the QR code. You may read more about QR codes on Wikipedia.
Here is an example of QR code for jQuery HowTo blog:
If you have a QR code reader on your mobile take a picture of it and it will open this website. Cool ha?!
Anyway, there are plenty of free online QR code generator sites, but no JavaScript and jQuery plugins/functions. So, I quickly searched for a free online QR code generator sites with “friendly” URL’s and put together a javascript and jQuery functions that generate QR barcode image’s URL for passed URLs. I used Kaywa & University of Bath services.
Here are javascript and jQuery QR code functions:
// JavaScript function
function qrcode(url, size){
if(typeof(size) == 'undefined') size = 8;
return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
}
qrcode('http://jquery-howto.blogspot.com');
// jQuery plugin
(function ($) {
$.fn.qrcode = function(url, size) {
if(typeof(size) == 'undefined') size = 8;
return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
}
})(jQuery);
$().qrcode('http://www.google.com');The code above utilizes Kaywa’s online QR code generator. You can specify image site as the second argument to the function. The size argument mut be between 1 and 40 and the generated image will 32 x your argument.
Here is javascript and jQuery code for University of Bath barcode generator:
If you have better solution, just tell me !
// JavaScript function
function qrcode(url){
return 'http://go.bath.ac.uk/qr/download?DATA='+url;
}
qrcode('http://jquery-howto.blogspot.com');
// jQuery plugin
(function ($) {
$.fn.qrcode = function(url) {
return 'http://go.bath.ac.uk/qr/download?DATA='+url;
}
})(jQuery);
$().qrcode('http://www.google.com');Cross domain AJAX querying with jQuery
This post IS NOT about jQuery’s JSONP support. This post is about how to make AJAX queries to domains other then yours. Basically how to achieve cross domain scripting with jQuery. The technique will help you resolve the access to restricted uri denied" code: "1012 problem.
Using this method for cross site scripting you will be able to:
Make AJAX queries to any domain even those that differ from your own;
Use any of $.get(), $.post(), $.ajax(), $getScript(), etc. jQuery AJAX functions as your query method.
But all these does not come free, you will need to put a proxy to between you and the rest of the world. This cross domain querying solution works because you actually loading the content from your own domain. You request the URL and the proxy script on your server actually loading the content from the internet and passing it over to you.
I created a sample PHP proxy that I used to get related news RSS feed for one of my projects.
The PHP script to use as a cross domain scripting proxy:I named the file proxy.php and made my AJAX request to this url. Here is a jQuery code example:
<?php
// Set your return content type
header('Content-type: application/xml');
// Website url to open
$daurl = 'http://feeds.feedburner.com/jQueryHowto';
// Get that website's content
$handle = fopen($daurl, "r");
// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>And this is how I overcame the jQuery cross site scripting problems. The bad news is that not all web hosting companies allow fopen() to other domains, but enable it on request. My web server was very strict on security but the script above worked well on it.
$("#rssFeeds").load("path/to/proxy.php", function(){
// Some callback functions
});If you have better solution, just tell me !
Showing progress with the Safari 4 multiple file upload
Andrea Giammarchi has taken the new Safari 4 implementation of multi input file upload functionality and has written an article on how to write the client and server to enable this.He shares the new XHR implementation:
var xhr = new XMLHttpRequest, upload = xhr.upload; upload.onload = function(){ console.log("Data fully sent"); }; xhr.open("post", page, true); xhr.send(binaryData);and the delves into a PHP server backend that groks things like X-File-Size and X-File-Name.
Then, he shows the client side code to push this all forward and packages it all up:
If you have better solution, just tell me !
Best way to load your JavaScript ...
I’ve come to the conclusion that there’s just one best practice for loading JavaScript without blocking:
1. Create two JavaScript files. The first contains just the code necessary to load JavaScript dynamically, the second contains everything else that’s necessary for the initial level of interactivity on the page.
2. Include the first JavaScript file with a tag at the bottom of the page, just inside.
3. Create a second tag that calls the function to load the second JavaScript file and contains any additional initialization code.A helper to make this happen could look like:
function loadScript(url, callback){ var script = document.createElement("script") script.type = "text/javascript"; if (script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState == "loaded" script.readyState == "complete"){ script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function(){ callback(); }; } script.src = url; document.getElementsByTagName("head")[0].appendChild(script); }In related news, the LABjs folk have updated their API from this:
$LAB .script("jquery.js") .block(function(){ $LAB .script("jquery.ui.js") .script("myplugin.jquery.js") .block(function(){ $LAB.script("initpage.js"); }); });To the simpler:
$LAB .script("jquery.js") .block() .script("jquery.ui.js") .script("myplugin.jquery.js") .block() .script("initpage.js");I seem to remember that Steve had some opinions on this API too :)
If you have better solution, just tell me !
Ajax Trace Console
Ajax Trace Console is a web control to render (only in debug mode) this html code :
<textarea id="TraceConsole">
to AJAX debugging.
JavaScript, C#, and ExtSharp
Colin Ramsay thinks that JavaScript and C# can be scarily similar as he shows an ExtJS example:
JAVASCRIPT:
var win = new Ext.Window({ title: 'Order Viewer', layout: 'border', width: 500, height: 500, modal: true, resizable: false, closable: false, draggable: false, items: [ frm, lst ] }); win.on('render', function() { load(5); }); win.show();
C#:
This works well for ExtJS since it is written in a style that leads itself to this similarity. Colin also points out ExtSharp, a project that lets you write your Ext application in C#:
If you have better solution, just tell me !