Javascript/Ajax/JQuery « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Javascript/Ajax/JQuery ’ Category

Detecting mobile browsers in Javascript

Posted by Vishal Sahu on December 18th, 2011

Hi,

In my recent grails project, i was working on mobile version of the application and needed to redirect users to the mobile version of our application, if they are accessing the application from any mobile device. I looked at various techniques/codes to detect mobile device and redirect users to the specific URL.


I encountered a simplest piece of code which worked in my case and thought it worth sharing.


Just put this code in the head section of you web page and it will redirect it to the specified URL if the device is mobile browser.

Code is:

<script type="text/javascript">

if (screen.width <= 699) {
document.location = "http://www.example.com/mobile-version.html";
}

</script>

References:-
http://css-tricks.com/snippets/javascript/redirect-mobile-devices
http://www.ianfernando.com/2011/how-to-redirect-mobile-traffic-to-a-mobile-friendly-page/
http://www.warriorforum.com/offline-marketing-discussions/376351-redirection-script-mobile-site.html


This worked for me.
Hope it helps.


Cheers!!!
Vishal Sahu
vishal@intelligrape.com
http://www.intelligrape.com

  • Share/Bookmark

Placeholder in html5

Posted by umar on May 15th, 2011

HTML5 has made the page designing an easy task. Placeholder is input field improvement in html5. Things that we were doing in past using combination of HTML and client side scripting language can be done in HTML5 using an attribute. One of the example is placeholder attribute used with input type text which automatically puts the placeholder attribute value in the text field if it is empty. This placeholder text is cleared automatically on focus and on focus out either the entered text or the placeholder value (if nothing was entered) is displayed.

html form

<form>
<code>
  <input name="fieldname" placeholder="Enter any keyword">
  <input type="submit" value="Search">
</code>
</form>

Support browser

IE Firefox Safari Chrome Opera
. 3.7+ 4.0+ 4.0+ 11.0+
  • Share/Bookmark

JQuery : create URL query string from JSON/Array

Posted by Amit Jain on May 4th, 2011

Hi Friends,
(more…)

  • Share/Bookmark

Change Input Type auto focus

Posted by umar on March 15th, 2011

This is little bit but it is very useful. This is input type equalto text when when cursor come in input then change type equalto password.

Embed in html

<input type="text" onblur="javascript:if(this.value==''){this.value='password',this.type='text'} else {this.type='password'}" onfocus="javascript:if(this.value=='password'){this.value=''} {this.type='password'}" value="password" tabindex="1" size="30" id="txtEmail" name="txtEmail">

This is Demo




Support browser

IE Firefox Safari Chrome Opera
6.0+ 3.5+ 3.0+ 3.0+ 10.5+
  • Share/Bookmark

Sorting in javascript

Posted by Sachin on March 13th, 2011

Recently in my project I needed to sort an object list on the basis of object name. For the same purpose I created the following function


function sortList(objList) {
 objList.sort(sortByName);
}

function sortByName(a, b) {
 var x = a.name;
 var y = b.name;
 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

This function sorts an object list on the basis of name of object. Hope it helps

Sachin Anand

sachin[at]intelligrape[dot]com

  • Share/Bookmark

Using Google Analytics for tracking Multiple Steps of a Webflow

Posted by Vivek Krishna on February 28th, 2011

In one of our projects, we are using a webflow for an order wizard. We needed to track the number of users converting a draft to a confirmed order using Google Analytics. This would have been simple if the URLs were different for each step. However, that is not the way webflows work and a similar URL is generated for multiple steps. After some searching around, we found that we could call a trackPageView method in Google Analytics API and set a name for the page being tracked. This could be done using

<script type="text/javascript">
    try {
        var pageTracker = _gat._getTracker("<ANALYTICS-KEY>");
        pageTracker._trackPageview("/enterDetails.html");
    } catch(err) {
    }
</script>

Replacing “/enterDetails.html” in each page with the corresponding step name did the trick. However, this is an old version of the Google Analytics API. Our application uses a newer version of the JavaScript code provided by Google.

In this, we had to use Virtual Page Tracking, which is a method explained in the Google Analytics API Docs under the section, Virtual Page Views. We had to write something like


<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'ANALYTICS-KEY']);
_gaq.push(['_trackPageview', '/enterDetails.html']);
(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

For usage on grails, we used a template, which takes in the pageName and uses /${controllerName}/${actionName}/${pageName} to  generate the virtual page name which is tracked. Now we are successfully tracking the conversions.

Hope this helps.

Vivek

http://in.linkedin.com/in/svivekkrishna

  • Share/Bookmark

Editable Label Tag and introduction to Effects Tag Lib

Posted by Kushal Likhi on February 19th, 2011

Lately i had some spare time, hence decided to utilise it for developing some cool GUI elements.

What is effects tag lib??

It is just a new tag lib which is intended to contain some cool grails tags for GUI manipulations.
new tags will be added to it on timely basis, this is the first post regarding this tag lib.

Editable Lable

this is the first tag in this tag lib. It is a cool GUI label which can be edited realtime.

Features:
1) Post-able as a form element.
2) easy value manipulation and extraction.
3) Tool Tip support.
4) Validate-able using, just assign class as you assign to any text field for validation.
5) style-able using css
6) Default value and blank handling
7) easy to use.

Details about the tag
tag usage:-

<etl:editableLable />

you can treat this tag as an input text field, it gives you similar behaviour

attributes:
1) name: for form support, the value is posted with the form with param.
2) class: class to be applied, for styling and validation.
3) id: id given to the input feild
4) value: value to be displayed on the lable
5) default: the value to be displayed in case user enters blank in the edit mode
6) size: the size of the input feild
7) tooltip: text to be displayed in tool tip. if nothing specified default tooltip text will be displayed. i.e. “click to edit”
8] tooltipclass: class assigned for styling the tooltip as per the page needs
NOTE: All attributes are not required.

DEMO:-

here is the demo to the tag:

Next Addition

# Image scroller filmstrip tag
# vertical image slider tag
# Editable paragraph tag
# safe string tag
# Drawable rounded border without images tag
# auto sizing-resizing tag
# relative positioning
# image slider normal
# picker tab(3X3) tag
# tool tip provider tag
# progress bar tag
# slider tag
# modal window
# modless window
# progress bar
# more/less box
# pie graph
# bar graph
keep looking………

Download:

Link coming soon!! within few days.. waiting for some more tags to be completed.

Regards
Kushal Likhi
www.intelligrape.com

  • Share/Bookmark

File Uploading using plupload plugin of jquery.

Posted by Anuj Aneja on February 14th, 2011

In my grails project i was having the requirement of having multiple file uploading, but in current implementation there was the problem of button being not loaded in Internet Explorer.For that i found plupload very cool to implement this. It has very cool feature of drag and drop and support for almost all browser. Actually what it does is based on the browser, get the Runtime of the browser.For Documentation, js and css refer link

In gsp we need to include the js of pluplaod api as shown below:

<link rel="stylesheet" href="${resource(dir: 'css/plupload/css', file: 'plupload.queue.css')}" type="text/css" media="screen">
<link rel="stylesheet" href="${resource(dir: 'css/plupload/css', file: 'jquery.ui.plupload.css')}" type="text/css" media="screen">
<g:set var="fileExtension" value="${new FileExtension()}"></g:set>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<p:javascript src='jquery-1.3.2'/>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "gears_init.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "browserplus-min.js")}"></script>
<!-- Load source versions of the plupload script files -->
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.gears.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.silverlight.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.flash.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.browserplus.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.html5.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "jquery.plupload.queue.js")}"></script>
<script type="text/javascript">
    var button = '${buttonId}';
</script>

Now we need to write script to load and bind the plupload plugin shown below:

	<script type="text/javascript">
    var runtimesList;
    if (navigator.userAgent.indexOf("Firefox")!=-1){
        runtimesList='silverlight,browserplus,html4,gears,flash,html5';
    }else{
        runtimesList='html5,silverlight,browserplus,html4,gears,flash';
    }
    $(function() {
        var uploader = new plupload.Uploader({
            runtimes : runtimesList,
            browse_button : 'pickfiles',
            url : url,
            flash_swf_url : '${resource(dir: "js/plupload", file: "plupload.flash.swf")}',
            silverlight_xap_url : '${resource(dir: "js/plupload", file: "plupload.silverlight.xap")}',
            filters : [
                {title : "Image files", extensions : "gif,png"},
                {title : "Zip files", extensions : "zip"}
            ]
        });

        uploader.bind('Init', function(up, params) {
        });

        uploader.bind('FilesAdded', function(up, files) {
            $.each(files, function(i, file) {
                $('#filelist').append('<div id="' + file.id + '"><span class="mcentd9d" style="font-size:12px; color:green;">File: ' + file.name + ' uploaded successfully!(' + plupload.formatSize(file.size) + ')<b></b><\/span>' + '</div>');
            });
        });

        uploader.bind('UploadFile', function(up, file) {

        });

        uploader.bind('UploadProgress', function(up, file) {
            $('#' + file.id + " b").html(file.percent + "%");
        });

        uploader.bind('QueueChanged', function(up) {
            $('#uploadfiles').click();
        });

        uploader.bind('FileUploaded', function(up) {

        });
        uploader.bind('Error', function(up) {
            alert('Error in uploading file');
        });

        $('#uploadfiles').click(function(e) {
            uploader.start();
            e.preventDefault();
        });
        uploader.init();
    });

</script>
	<div class="attachment">
               <div id="filelist"></div>
                      <a href="#" class="plupload_button plupload_add" id="pickfiles" style="position: relative; z-index: 0; ">Select File</a>
                      <input type='hidden' id="uploadfiles"/>
          </div>

Now we need to handle the saving part of the file,for each file uploaded in Queue there is separate call to
the action.It saves the file to the filePath specified.

def saveAttachment={
      def files = request.getFileMap()
      def file=files.get("file")
      String fileName = file.getOriginalFilename()
      byte[] data=file.getBytes()
      File dir=new File(filePath)//some path...
      if(!dir.exists()){
         dir.mkdirs()
      }
      File actualFile=new File(filePath, fileName)
      actualFile.withOutputStream {out ->
             out.write data
      }
}

Disclaimer: As in some cases you might want to can the upload of all the files as there is a different call to action of you can save there files in session, but session for this plupload is different from current user session so you will have to make your own session handling for that!!!

Note:The total length of files upload and and total uploaded differs in case IE and Firefox. The comments and any suggestions are welcomed.

Hope it help you guys! Cheer! :)

Anuj Aneja

http://www.Intelligrape.com

  • Share/Bookmark

JQGrid Expanding SubGrid on page load

Posted by Tarun Pareek on February 13th, 2011

Hi,
 
Recently guys, i faced problem while expanding the JQGrid SubGrid onLoad of the page.
 
Initially, i used the following code on gridComplete Event of JQGrid, Using the code given below, i am only able to expand grid but without data populated in subgrid.

gridComplete: function() {
                var rowIds = $("#testTable").getDataIDs();
                $.each(rowIds, function (index, rowId) {
                        $("#testTable").expandSubGridRow(rowId);                   
                });
            }

After trying different ways, and many efforts i came up with this solution and it worked for me.
Solution to above problem given below :

gridComplete: function() {
                var timeOut = 50;
                var rowIds = $("#testTable").getDataIDs();
                $.each(rowIds, function (index, rowId) {
                    setTimeout(function() {
                        $("#testTable").expandSubGridRow(rowId);
                    }, timeOut);
                    timeOut = timeOut + 200;
                });
            }

It worked for me. Hope it help you too.

Thanks & regards,
Tarun Pareek
LinkedIn

  • Share/Bookmark

Grails taglib and JavaScript file

Posted by Bhagwat Kumar on January 16th, 2011

We use internationalization feature in grails using message tag in GSP pages. However arbitrary Groovy/Grails (e.g. tags) code can not be used in JavaScript as they are not executed on server side. To overcome this I used the following way :

Declare a JSON object in js file or any where else so that this object is global one. Create a global JavaScript function that can populate this JSON object. Here is the sample code:


var i18nmessages={};

function updateConfigurationMap(newConfigurationMap) {
	for(key in newConfigurationMap){
		i18nmessages[key] = newConfigurationMap[key];
	}
/*
	//or in jQuery way
	jQuery.each(newConfiguration, function(key, val) {
		i18nmessages[key] = val
	});
*/
}

Now you can write code like below inside HTML head tag in GSP pages to populate the i18nmessages JSON map:


<script type="text/javascript">

 updateConfigurationMap({

   noResultError : '${message(code:'project.noResultError'')}.encodeAsHTML()',

   rangeError : '${message(code:'project.rangeError', args:[50, 100]).encodeAsHTML()}',

   ajaxCallUrl : '${createLink(controller:'myController', action: 'myAction')}',

   deleteImagePath : '${resource(dir:'images', file:'myimage.png')}'

 });

</script>

After execution of the above GSP code considering that the JavaScript code written above has executed, you can use messages like this in javascript :


function findResult(){
	alert("Error occurred during processing : "+i18nmessages.noResultError)
}

function getRemoteData(dataToSend){
       /*  note that you can not use createLink grails tag here  */
	jQuery.get(i18nmessages.ajaxCallUrl+"?"+dataToSend, function(response){
		// Process response here.
	})
}

function insertDeleteImage(){
       /* As you can not use resource tag of grails here */
	jQuery('selector').append("<img src='"+ i18nmessages.deleteImagePath +"' />")
}

Obviously there is a drawback with this approach that the JavaScript for setting messages can not be cached in browser. But the advantage is that you are free to use arbitrary Server side code to generate messages. As you have noticed in above code snippet the URL for ajax call and image paths generated using Grails tags can not be used inside the js files.

Another idea will be to create separate js files name ending with language suffix(e.g. *-en.js, *-sv.js etc) for each language your app support. Populate the i18nmessages there. Use appropriate js file depending on the request locale(e.g. session.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'). This way you can enable caching of js files in browser but you are limited to messages with static content only.



Please share your ideas how you solved this situation.


Cheers!
~~Bhagwat Kumar~~
bhagwat(at)intelligrape(dot)com

  • Share/Bookmark