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.
$.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&#M jQuery 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 !
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=SomeOtherValue |
Calling 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 !
JQuery to change the width of a mulitvalued lookup field in SharePoint and to hide the Workspace field in an event list.
The script to change the width of multivalued lookup fields:
<script type="text/javascript">
$(document).ready(function()
{
$("select[id*='<INSERT_YOUR_FIELDNAME>']").parent().width(300);
$("select[id*='<INSERT_YOUR_FIELDNAME>']").parent().height(200);
$("select[id*='<INSERT_YOUR_FIELDNAME>']").width(300);
});
</script>
The script to hide the workspace checkbox in an event list: This first bit of script hides the ‘Workspace’checkbox in the NewForm and the EditForm. The script to hide the workspace field from the DispForm.aspx:
<script type="text/javascript"> $(document).ready(function() { $("a[name='SPBookmark_WorkspaceLink']").parent().parent().parent().hide(); }); </script> |
<script type="text/javascript"> $(document).ready(function() { $("a[name='SPBookmark_WorkspaceLink']").parent().parent().parent().hide(); }); </script> |
There are several ways to add the script to the pages. For the Lookup fields I used the I descibe in this blog post. For the Event list, I created custom EditForm, NewForm and DispForm pages and added the script to those pages directly.
If you have better solution, just tell me !
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 !
This plugin adds the ability to update multiple elements with a single Ajax response.
Usage
$.superLoad( options );
The options are the same as taken by the jQuery.ajax( ) method, with
the following observations:
dataType: defaults to 'html'
success: will be called after the content is updated on the page.
Expected response format:
<div class="ajax-response">
<div class="ajax-content" title="!update #div1">
<p>
Anything inside this div will be used to update the #div1 element
like $('#div1').html( $(thisDiv).html() );
</p>
</div>
<div class="ajax-content" title="!appendTo #div2">
<p>
Anything inside this div will be appended to the #div2 element
like $('#div2').append( $(thisDiv).html() );
</p>
</div>
<div class="ajax-content" title="!prependTo #div3">
<p>
Anything inside this div will be prepended to the #div3 element
like $('#div3').prepend( $(thisDiv).html() );
</p>
</div>
<div class="ajax-content" title="#div4">
<p>
if the !command is not given, !update will be assumed
</p>
</div>
<div class="ajax-content" title="!replaceWith #div5">
<p>
Replaces #div5 with this P element
</p>
</div>
<script>
//each script tag will be evaluated after the content has been applied.
doStuff();
</script>
<script>
doOtherStuff();
</script>
</div>
The title attribute:
- The ajax-content element's title attribute is used to determine what to do with the content:
- The format is: "!command selector"
- "!command": defaults to !update
- !update: replaces the inner HTML of the selected element(s) with the inner HTML of the ajax-content
- !prependTo: adds the inner HTML of the ajax-content to the top of the inner HTML of the selected element(s)
- !appendTo: adds the inner HTML of the ajax-content to the bottom of the inner HTML of the selected element(s)
- !other: Beyond the above 3 standard !commands, one can also simply pass the name of any valid jQuery command (default of from a plugin) as long as the command is able to be applied to the selected element(s) and takes the new content as its argument.
Investigating my visitors statistics, I noticed that there were some users who were interested in adding and using jQuery on their Blogger.com (Blogspot.com) accounts. Adding jQuery library to your Blogger/Blogspot blog is not difficult. All you have to do is to add one line of code to your template’s header.
Here is the code to add to your blogger template’s header:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6 /jquery.min.js" type="text/javascript"></script> |
NOTE:
You don’t even need to upload jquery.js file on any other hosting Google will host it for your.
Instruction for adding jQuery to Blogger:
Login to your dashboard;
Choose your blog;
From the top menu select “Layout”;
Then select “Edit HTML” sub-menu;
Add the above code just below tag (or alternatively, just above tag)
If you have better solution, just tell me !
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 !
Today I have a quick note for you that will probably save you time someday. Basically it’s a workaround for a bug when you have parent element with children elements and parent element has mouseover or mouseout event. Moving your mouse over children elements may fire mouseout event of their parent. This is caused by event bubbling / propagation and if you would like to have a quick solution just read the solution at the bottom of this post. If you would like to understand it in more details please search Google for event propagation.
The problem: When you have mouseover and mouseout events bound to some element on you page with children elements. Hovering over children element fires parent’s mouseover and/or mouseout event.
The solution: The solution to this error is to use mouseenter and mouseleave events instead of mouseover and mouseout.
The reason:
This solution works because mouseover and mouseout events do not bubble from child to parent element.
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 1100ms |
Usually 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.
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 !
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:
// 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'); |
If you have better solution, just tell me !
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:<?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); } ?> |
I named the file proxy.php and made my AJAX request to this url. Here is a jQuery code example:
$("#rssFeeds").load("path/to/proxy.php", function(){ // Some callback functions }); |
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.
If you have better solution, just tell me !
This post is about removing a table row on user click. I needed this functionality for a project of mine. Online application had a table with data that user can dynamically add and remove. With progressive enhancement I also need to add a functionality to one of the tables that enables users to delete table rows when that table row is clicked.
jQuery code to delete clicked table row came out to be surprisingly short, only 3 lines of code.
// Select all table cells to bind a click event $('table td').click(function(){ $(this).parent().remove(); }); |
Here, we are first selecting all table cells to bind our click event. On user click to any table cell click event fires. In the click event we are removing
’s parent, which is |
, thus removing whole row.By popular user demand I’m including an example that lets deleting a table row on delete image click. Here is our HTML table:
<table> <tr> <td>row 1, cell 1</td> <td><img class="delete" src="del.gif" /></td> </tr> <tr> <td>row 2, cell 1</td> <td><img class="delete" src="del.gif" /></td> </tr> </table> |
Here is jQuery code to delete a row on delete image click:
$('table td img.delete').click(function(){ $(this).parent().parent().remove(); }); |
See demos Click here.
Bonus: Also delete a table row from database
The code above is enough if you don’t need to also delete a record from your database table. In my case I had to set up a server side code to do that. With one extra AJAX call to my server side script the functionality was ready.
$('table td').click(function(){ $.get('deleteRow.php', {id: $(this).parent().attr('id')}, function(){ $(this).parent().remove(); }); }); |
In the jQuery code above, instead of removing table row straight away we are making an AJAX call to our server side code that also removes that row from our database and then on AJAX call completion we removing table row.
If you have better solution, just tell me !
The animation is really quite simple. We’ll use jQuery to animate the opacity of the <span> tag. Remember that the <span> tag displays the “hover” state of the image. Hence, when the <span> is visible, the link takes the “hover” appearance. We’ll need the “hover” state to be invisible when the page loads. We can do this by setting the opacity of the <span> tag to “0″:
$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// the rest of the code will go here
});
Placing the code inside of “$(function() { … });” tells the browser to execute the code when the document has loaded. The code that we’ll use to do the animation is as follows:
// on mouse over
$("ul#menu span").hover(function () {
// animate opacity to full
$(this).stop().animate({
opacity: 1
}, 'slow');
},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({
opacity: 0
}, 'slow');
});
Hence the entire Javascript used is as follows:
<!-- Include jQuery Library -->
<script src="jquery-1.2.2.pack.js" type="text/javascript"></script>
<!-- Let's do the animation -->
<script type="text/javascript">
$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// on mouse over
$("ul#menu span").hover(function () {
// animate opacity to full
$(this).stop().animate({
opacity: 1
}, "slow");
},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({
opacity: 0
}, "slow");
});
});
</script>
Notice that we first include the jQuery library. You can learn more about jQuery animations by reading up on the
documentation. One final addition to the CSS is required to ensure that the mouse cursor is display as a pointer when hovering over the <span> tag:ul#menu li a span:hover {
cursor:pointer;
}
The full source code can be accessed via the demonstration page. I should just add that whilst this code seems to work well with FireFox and IE7, IE6 might (and probably will) be a different story.
If you have better solution, just tell me !
JScript IntelliSense: Working with jQuery
We have good news for jQuery fans. The hotfix we released today fixes a bug in IntelliSense where it would fail with jQuery. Any page with jQuery should just work now. While experimenting with this new-found functionality today, I found annotating the library with a few XML Doc Comments really made a big difference. The key is to add a return type of "jQuery" like this:

Here's some jQuery chaining with IntelliSense:


There were only a few functions that (due to the way they were declared) were not able to be annotated. Special thanks to Brennan where I borrowed the comments from. If anyone will be making a fully annotated version of jQuery, I'd be happy to post a link to it from here.