Bookmark and Share
Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Friday, September 16, 2011

Google+ +1Button examples

You can add the 1+ button to your pages in various ways, here are 4 live examples, the latest with javascript integration:
Adding the 1+ button like this


is really simple, just add this line of code :
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<g:plusone></g:plusone>

Another useful option is to include the button using asynchronous rendering:

<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>

Another option to add a +1 button that reference another web site, here is an example, referencing google+ api’s page:
Google APIs!

And the code used:

<g:plusone size="tall" annotation="Google+ api page rocks!" expandto="top" href="http://developers.google.com/+/api/"></g:plusone>



You cal also call a function after the user's click, you can alert a message to the user or access a special page when the user appreciates your page:

<g:plusone annotation="Code recipes rocks!" size="tall"  callback="doSomethingAfterClick"></g:plusone>


And the javascript code:
<g:plusone annotation="Code recipes rocks!" callback="doSomethingAfterClick" size="tall">;/g:plusone>

<script>

function doSomethingAfterClick(jsonParam)
{
    if (jsonParam.state=='on')
        alert("Thank you dear!");
    else 
        alert("Oh no!!! I'm really sad!");
}

</script>

Hope it helps!

Wednesday, June 29, 2011

Processing.js is emerging….

Processing.js is the porting of processing language on the HTML5 world.

You can use it in two ways: using the original processing code, a dialect of the java language translated on the fly by the processing JavaScript code or using the processing.api.js file, writing only JavaScript.

The Processing language was born based on a great idea: enable programmers with only one line of code to see something on the video.

Processing language is like a Lego game, you have bricks and you can create great works using only a few of them.

Here is a great site using processing: http://numberpicture.com/picture/search

image

And here is the official processing site: http://processingjs.org/

image

Note that the header in the web site is “interactive” !

Tuesday, June 28, 2011

JavaScript Trim on Internet Explorer…

If you are writing scripts for firefox, chrome, safari and ie and you are using the trim function… don’t forget that IE does’n support it!

In order to enable it you need to add the script:

if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}


That’s all!

Wednesday, June 22, 2011

Nations of the world in javascript array

If you need a list on continents and nations in javascript format here is the code:

var continents =
[
["Africa","Algeria,Angola,Benin,Botswana,Burkina,Burundi,Cameroon,Cape Verde,Central African Republic,Chad,Comoros,Congo,Congo, Democratic Republic of,Djibouti,Egypt,Equatorial Guinea,Eritrea,Ethiopia,Gabon,Gambia,Ghana,Guinea,Guinea-Bissau,Ivory Coast,Kenya,Lesotho,Liberia,Libya,Madagascar,Malawi,Mali,Mauritania,Mauritius,Morocco,Mozambique,Namibia,Niger,Nigeria,Rwanda,Sao Tome and Principe,Senegal,Seychelles,Sierra Leone,Somalia,South Africa,Sudan,Swaziland,Tanzania,Togo,Tunisia,Uganda,Zambia,Zimbabwe"],
["Asia","Bangladesh,Bhutan,Brunei,Burma (Myanmar),Cambodia,China,East Timor,India,Indonesia,Japan,Kazakstan,Korea,North,Korea, South,Laos,Malaysia,Maldives,Mongolia,Nepal,Philippines,Russian Federation,Singapore,Sri Lanka,Thailand,Vietnam"],
["Europe","Albania,Andorra,Armenia,Austria,Azerbaijan,Belarus,Belgium,Bosnia and Herzegovina,Bulgaria,Croatia,Cyprus,Czech Republic,Denmark,Estonia,Finland,France,Georgia,Germany,Greece,Hungary,Iceland,Ireland,Italy,Latvia,Liechtenstein,Lithuania,Luxembourg,Macedonia,Malta,Moldova,Monaco,Montenegro,Netherlands,Norway,Poland,Portugal,Romania,San Marino,Serbia,Slovakia,Slovenia,Spain,Sweden,Switzerland,Ukraine,United Kingdom,Vatican City"],
["North America","Antigua and Barbuda,Bahamas,Barbados,Belize,Canada,Costa Rica,Cuba,Dominica,Dominican Republic,El Salvador,Grenada,Guatemala,Haiti,Honduras,Jamaica,Mexico,Nicaragua,Panama,Saint Kitts and Nevis,Saint Lucia,Saint Vincent and the Grenadines,Trinidad and Tobago,United States"],
["Oceania","Australia,Fiji,Kiribati,Marshall Islands,Micronesia,Nauru,New Zealand,Palau,Papua New Guinea,Samoa,Solomon Islands,Tonga,Tuvalu,Vanuatu"],
["South America","Argentina,Bolivia,Brazil,Chile,Colombia,Ecuador,Guyana,Paraguay,Peru,Suriname,Uruguay,Venezuela"],
["Middle East","Afghanistan,Bahrain,Iran,Iraq,Israel,Jordan,Kuwait,Kyrgyzstan,Lebanon,Oman,Pakistan,Qatar,Saudi Arabia,Syria,Tajikistan,Turkey,Turkmenistan,United Arab Emirates,Uzbekistan,Yemen"]
];

 

This is useful if you need to find using google geolocation the continent of a nation.

Here is the firebug console:

image

hope it helps!

Wednesday, May 18, 2011

Javascript HTML encoding/decoding utility

Today I found a great script for encoding and decoding HTML on the browser:

http://www.strictly-software.com/htmlencode

The library is located under http://www.strictly-software.com/scripts/downloads/encoder.js

The usage is really easy:

Encoder.EncodeType = "entity";

var encoded = Encoder.htmlEncode(document.getElementById('input'))

var decoded = Encoder.htmlDecode(encoded);


That’s all!

Thursday, November 11, 2010

JQuery: HOWTO Add Validator To Your Forms

Here is a simple way to add Input validation to your ASP.NET code using the JQuery Validator plugin.

1) Add a reference to the validator javascript library

<script src="scripts/jquery.validate.min.js" type="text/javascript"></script>


2) Add Css class to your input, example:


<asp:TextBox ID="txtFirstname" runat="server" Text='<%# Bind( "Firstname" ) %>' CssClass="required"></asp:TextBox>

or for a required email:

<asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind( "Email" ) %>' CssClass="required email"></asp:TextBox>


3) Call the “validate” method:


$(document).ready(function() {
$("#aspnetForm").validate();
}


4) If you have custom regular expressions loaded from server you need to:


Add on the server side an attribute to the the text elements with the regular expression:

 

txtEmail.Attributes.Add("regexp", "your regular expression rule" );

Add a custom validator via Javascript:


$.validator.addMethod(
"regex",
function(value, element, regexp) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
'<%= GetRes("Your message from sderver") %>'
);


apply the validation rule to all elements with a “regexp” attribute existing:

if ($('INPUT[regexp]').length > 0) {
$('INPUT[regexp]').rules("add", { regex: $(this).attr('regexp') });
}









5) If you need to change the default validation messages you can use this code:


jQuery.extend(jQuery.validator.messages, {
required: '<%= GetRes("Your_String_Id") %>'
});

GetRes is an internal helper function, it loads a string from the resources.

 

Hope it helps!

Tuesday, August 03, 2010

How to replace Flash with an Image for IPad/IPhone & disabled flash browsers

If your web site users are using IPad or IPhone or simply if they disabled flash on their browser you need to replace the ugly imageicon with a beautiful image.

Here is the magic script, copied from the web site http://www.kirupa.com/developer/mx/detection.htm, the script shows the swf flash or replaces it with an image if Flash is not supported.

<SCRIPT LANGUAGE=JavaScript1.1>
<!--
var MM_contentVersion = 6;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
var words = navigator.plugins["Shockwave Flash"].description.split(" ");
for (var i = 0; i < words.length; ++i)
{
if (isNaN(parseInt(words[i])))
continue;
var MM_PluginVersion = words[i];
}
var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0
&& (navigator.appVersion.indexOf("Win") != -1)) {
document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
document.write('on error resume next \n');
document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
document.write('</SCR' + 'IPT\> \n');
}
if ( MM_FlashCanPlay ) {
document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
document.write(' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" ');
document.write(' ID="script" WIDTH="300" HEIGHT="200" ALIGN="">');
document.write(' <PARAM NAME=movie VALUE="script.swf"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#FFFFFF> ');
document.write(' <EMBED src="script.swf" quality=high bgcolor=#FFFFFF ');
document.write(' swLiveConnect=FALSE WIDTH="300" HEIGHT="200" NAME="script" ALIGN=""');
document.write(' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">');
document.write(' </EMBED>');
document.write(' </OBJECT>');
} else{
document.write('<IMG SRC="script.gif" WIDTH="300" HEIGHT="200" usemap="#script" BORDER=0>');
}
//-->
</SCRIPT><NOSCRIPT><IMG SRC="script.gif" WIDTH="300" HEIGHT="200" usemap="#script" BORDER=0></NOSCRIPT>

 

Replace the script.swf file name with your flash and replace the script.gif image with your replacement image name.


This script is tested and working!


 

Thursday, July 29, 2010

How To avoid double click on ASP.NET buttons…

A common task when you develop web applications is to avoid double clicking on buttons, the user may send two or more times the form content and sometimes you may have unexpected results like double payments and other nasty effects.

Here is the code snippet used to avoid this behavior, btnSendResults is the ASP.NET buttons that causes the postback event, use in the  Page_Load event:

btnSendResults.Attributes.Add("onclick", "this.disabled=true;" + ClientScript.GetPostBackEventReference(btnSendResults, "")+";return false;");
Hope it helps!

Monday, November 30, 2009

JQuery assorted tips

Here are some useful JQuery 1.2.7 code snippets:

//Select the cheched checbox:
$('#myId').find('input[@type=radio][@checked]')
//Get an array of text of the selected SELECT
var elems = $.map($('#myId).find('select :selected'),function(a){return $(a).text();})
//Get an array of the values of the selected SELECT
var txtelems = $.map($('#myId).find('[@id=innerElementId]').find('input'),function(a){return $(a).val();});
//Set the title on a element
$(idTxtSearch).attr('title','my title');
//Focus a textbox (INPUT field)
$(idTxtSearch).focus();
//reset the value of a textbox (INPUT field)
$(idTxtSearch).val('');
//not JQuery, add a trim function to the JavaScript String object
String.prototype.trim = function ()
{
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
//ASP.NET + JQuery + blockUI
//Call the postback on a button after having blocked the page
//Note that the __doPostBack requires the name of the element, not the Id, asp.net rules.
$.blockUI({message:$('#myId').html()});
__doPostBack($('#<%= myAspNetBtn.ClientID %>').attr('name'), '');
//Attach the keyup event of a textvox
$().keyup(function(e){myFunction();});
//function for the blur and focus events
searchBoxes.focus(function(e){$(this).addClass("mycss");});
searchBoxes.blur(function(e){$(this).removeClass("mycss");});
//reset all the checkboxes inside an element
$('#myid > input[@type=radio]').attr('checked','')
//find the first DIV inside a table row that contains a value
if ($('#myid').find('tr:contains(thestring)').find('div:eq(1)').length>0)
//reset an element and add some HTML
$('#myid').empty().append(someHTML);
//find all visible elements inside an element with class myClass
$('.myClass').find('*').css("visibility","visible");
//change the source image on some images 
$(elemDiv).find('IMG[@src*="myvalue"]').attr('src','images/oem/newimg.png');
//add the nowrap attribute to all TDs
$(elemDiv).find('TD').attr('nowrap','nowrap');
//hide an element 
$('.myClass').hide();
//disable a button
btn.attr('disabled','disabled');
//find the first element with the same attribute and get the display attribute
$("[@myattr='my-row']:first").css('display');
//Toggle a class on a element
element.toggleClass("myClass");
//Execute script after the page load
$(document).ready(function()
{
//some js here;
});
//find the first image inside an element and chenge the image source
element.children('img:first').attr('src',newSrc);
//duplicate an HTML element
$('#myId').clone();
//get the url of an anchor with id=myId
var sUrl = $("a[@id='myId']").attr('href');
//hide all anchors inside an element
$('#myId').find('A').css('display','none');
//get the text of an element
var text = $('#myId').text();
//disable a button
$('#myId').attr('disabled', true);
//click a button after the load of the page
$(document).ready(function(){$('#myId').click()});
//check all visible checkboxes inside a table
function selectAllVisibleCheckBox(idTable)
{
$("#" + idTable).find("input[@type$='checkbox']").each(function()
{
if ($(this).parents("TR").css("display")!='none')
this.checked=true;
}
);
return false;
}
//call the classical HelloWorld asmx web service using JQuery
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebServices.asmx/HelloWorld",
data: "{'msg':'hello!'}",
dataType: "json"
});
 

Wednesday, April 22, 2009

HOWTO NOT develop a web login page

Yesterday I was mining some information about bar codes on google, and I found this page:

After some surfing I found a login page:
zrclip_002n5df8c113.png
Damnn... I neeed a  password!
Here is the viewsource of the page:

Interesting, the Archivio checks with an ajax service...
Here is the code of the Archivio function:

Uhmmm... flag? Let me find on the upper code....

Ok, now we try one of these flags...:

Bingo! Here is the magical access to the page.

Don't hide the key of your house near the house door..

Tuesday, April 15, 2008

Enable/Disable ASP.NET AJAX Timer using JavaScript

This function controls an asp.net Timer using Javascript:

var timerServiceStatus = $get('<%= TimerServiceStatus.ClientID %>').control;

timerServiceStatus._startTimer();//Timer start

timerServiceStatus._stopTimer(); //Timer stop