Archive

Posts Tagged ‘JavaScript’

jQuery: Plugins to handle long click and taphold events

December 3rd, 2012 1 comment

jQuery plugin to catch a long click event

Below is a simple jQuery plugin to catch a long click or long press:

(function ($) {
  $.fn.longClick = function (callback, timeout) {
   // bind to element's mousedown event to track the longclick's beginning
   $(this).mousedown(function (event) {
    // save the initial event object
    var initialEvent = event;
    // set the delay after which the callback will be called
    var timer = window.setTimeout(function () { callback(initialEvent); }, timeout);
    // bind to global mouseup event for clearance
    $(document).mouseup(function () {
      // clear timer
      window.clearTimeout(timer);
      // unbind from global mouseup event
      $(document).unbind("mouseup");
      return true;
      // use 'return false;' if you need to prevent default handler and 
      // stop event bubbling
    });
     return true;
     // use 'return false;' if you need to prevent default handler and 
     // stop event bubbling
   });
  };
})(jQuery);

...
// using
(function ($) {
  $("#someDiv").longClick(function (e) { 
              alert($(e.target).attr("id") + " was clicked"); }, 
              1500);	
})(jQuery);

The plugin accepts a callback function that will be called once a long click event occurred and a timeout in milliseconds saying how long user should keep button pressed to produce the long click.

jQuery plugin to catch a taphold event

The same long click for iPad is usually called taphold and can be implemented as follows:

(function ($) {
  $.fn.taphold = function (callback, timeout) {
   // bind to element's touchstart event to track the taphold's beginning
   $(this).bind("touchstart", function (event) {
    // save the initial event object
    var initialEvent = event;
    // set the delay after which the callback will be called
    var timer = window.setTimeout(function () { callback(initialEvent); }, timeout);
    // bind to global touchend and touchcancel events for clearance
    $(document).bind("touchend touchcancel", function () {
      // clear timer
      window.clearTimeout(timer);
      // unbind from touchend and touchcancel events
      $(document).unbind("touchend touchcancel");                
      return true;
      // use 'return false;' if you need to prevent default handler and 
      // stop event bubbling
    });            
    return true;            
    // use 'return false;' if you need to prevent default handler and 
    // stop event bubbling
   });
  };
})(jQuery);

...
// using
(function ($) {
  $("#someDiv").taphold(function () { 
               alert($(e.target).attr("id") + " was tapholded"); }, 
               1500);
})(jQuery);

The only difference from the previous plugin is that touchable device’s events are used.

Combined jQuery plugin to catch both long click and taphold events

Two shown above plugins can be quite easily combined in one. The new plugin checks if the current device is an iPad and, if so, deals with such iPad events as touchstart, touchend and touchcancel; otherwise, it uses traditional mousedown and mouseup.

(function ($) {
 $.fn.longclick = function (callback, timeout) {
   var isIPad = $.isIPad();

   var startEvents = isIPad ? "touchstart" :           "mousedown";
   var endEvents   = isIPad ? "touchend touchcancel" : "mouseup";

   $(this).bind(startEvents, function (event) {
    // save the initial event object
    var initialEvent = event;
    // set delay after which the callback will be called
    var timer = window.setTimeout(function () { callback(initialEvent); }, timeout);
    // bind to global event(s) for clearance
    $(document).bind(endEvents, function () {
        // clear timer
        window.clearTimeout(timer);
        // reset global event handlers
        $(document).unbind(endEvents);
        return true;
        // use 'return false;' if you need to prevent default handler and 
        // stop event bubbling
    });
    return true;
    // use 'return false;' if you need to prevent default handler and 
    // stop event bubbling
   });
 };
})(jQuery);

...
// using
(function ($) {
    $("#someDiv").longclick(function () { 
             alert($(e.target).attr("id") + " was clicked"); }, 
             1500);
})(jQuery);

Note that the isIPad plugin was described in the post – jQuery: Plugins to detect iPad and iPhone devices.

Related posts:
Categories: iPad, JavaScript, jQuery Tags: , ,

jQuery: Plugins to detect iPad and iPhone devices

November 30th, 2012 No comments

jQuery plugin for iPad detection

Below is a simple jQuery plugin to detect whether a page is opened in an iPad:

(function ($) {
    $.isIPad = function () {        
        return (typeof navigator != "undefined" && 
               navigator && navigator.userAgent && 
               navigator.userAgent.match(/iPad/i) != null);
    };
})(jQuery);

...
// using
$(function(){
    if($.isIPad())
        alert('Hello, iPad');
});

jQuery plugin for iPhone detection

The next plugin allows to detect an iPhone:

(function ($) {
    $.isIPhone = function () {
        if(!$.isIPad())
            return (typeof navigator != "undefined" && 
               navigator && navigator.userAgent && 
               (navigator.userAgent.match(/iPhone/i) != null || 
                navigator.userAgent.match(/iPod/i) != null));
        return false;        
    };
})(jQuery);

...
// using
$(function(){
    if($.isIPhone())
        alert('Hello, iPhone');
});

Note, initially I check if the device is an iPad and only then try to identify it as an iPhone. I do so because people reports that some iPad browsers/applications use substring ‘iPhone’ in their userAgents along with the expected ‘iPad’. For example, such behavior was noticed in Facebook UIWebView.

jQuery plugin for Apple mobile device detection

To detect any Apple mobile devices (iPad, iPhone or iPod) you can use the following jQuery plugin:

(function ($) {
    $.isAppleMobile = function () {
        return (typeof navigator != "undefined" && 
               navigator && navigator.userAgent && 
               navigator.userAgent.match(/(iPad|iPhone|iPod)/i) != null);
    };
})(jQuery);

...
// using
$(function(){
    if($.isAppleMobile())
        alert('Hello, Apple device');
});
Related posts:

JavaScript: How to determine whether a variable has a valid value

November 29th, 2012 No comments

    A good way to examine whether a variable (or object’s field) has a valid value looks like the following:

if( variable /* obj.field */ ) {
}

This statement allows to check if the value is null (explicit assignment of null to variable happened) or undefined (variable wasn’t initialized). To be more precise it returns true when the variable is not

  • null
  • undefined
  • NaN
  • empty string (“”)
  • 0
  • false

Mostly, such validity check is more than enough for further safe treating with the variable. However, we’ll get the “‘variable’ is undefined error” if the variable is undeclared. In this case we have to perform the following check in advance:

if(typeof variable !== 'undefined') {    
}

Of course, if you are pretty sure that the variable exists (is declared), you can omit the typeof check. But if you deal with something going from an external library or source, I recommend having it. So, gathering all together, we obtain the following code:

if(typeof variable !== 'undefined' && variable) {    
}

In some forums, people from time to time suggest to wrap such check into a function. Let’s assume we have such function:

function isValid(obj) {    
  return typeof obj !== 'undefined' && obj;
}

However, it doesn’t make sense at all as you can’t call the function, passing an undeclared variable, in any case. The mentioned above error is thrown whenever you try addressing to the unknown variable:

if(isValid(varibale)) // throw "'variable' is undefined error", 
                      // if the variable doesn't exist
  ...

Thus, in case of undeclared variable, we have to have inline typeof check. In all other cases, it’s enough to have simple if(variable). So, using variables and objects likely declared outside of my code, I examine them like in the sample below:

if(typeof navigator != "undefined" && navigator && navigator.userAgent)
     alert(navigator.userAgent);
Categories: JavaScript, jQuery Tags: ,

jQuery: IsNullOrEmpty plugin for jQuery

November 20th, 2012 No comments

    I was a bit disappointed when couldn’t find in jQuery library a method similar to String.IsNullOrEmpty from C#. So, below is a simple jQuery plugin to examine whether the passed string is empty or null.

(function ($) {
    $.isNullOrEmpty = function (str) {
        return !str || $.trim(str) === ""; // the trim method is provided by jQuery 
    };
})(jQuery);

Some samples of use

var res = $.isNullOrEmpty(''); // true
res = $.isNullOrEmpty("bla-bla-bla"); // false
res = $.isNullOrEmpty(null); // true
res = $.isNullOrEmpty(); // true
Related posts:
Categories: JavaScript, jQuery Tags: ,

SharePoint: Issue with calling an asmx web service in SharePoint 2010 through jQuery

November 20th, 2012 No comments

    After migration a SharePoint 2007 application to SharePoint 2010 my jQuery scripts communicating with asmx web services stopped working. The error I got was a 500 Internal Server Error. The scripts looks as follows:

$.ajax({
  type: "POST",
  url:  "http://someserver/someapp/_layouts/Services/Products.asmx/GetProductByCountry",

  data:        JSON.stringify({ countryCode: "USA" }),
  dataType:    "json",
  contentType: 'application/json; charset=utf-8',
  context:     this,

  success: function (data) {
		     alert(data.d);
           },
  error:   function (XMLHttpRequest, textStatus, errorThrown) {
		     alert(textStatus);
           }
});

Note: The JSON object mentioned in the script is defined in the json2.js available at http://www.json.org.

This issue can be solved by adding an appropriate <webServices> section to the SharePoint application’s web.config (in my case it’s located at C:\inetpub\wwwroot\wss\VirtualDirectories\80). So, find the global <system.web> section in your web.config and make changes so that the result would look like the following:

<system.web>
  <webServices>
    <protocols>
      <add name="HttpGet" />
      <add name="HttpPost" />
    </protocols>
  </webServices>
...
</system.web>

However, from the security point of view such solution is not ideal as it allows external access through the HTTP-GET and HTTP-POST messaging protocols to all your XML web services. So, it’s better to specify the access protocols for each web service separately, not affecting other ones. The <location> element added to the root <configuration> element provides us with this capability. The sample below defines the protocols for accessing the web service reachable by the specified path:

<configuration>
...
  <location path="_layouts/Services/Products.asmx">
    <system.web>
      <webServices>
        <protocols>
          <add name="HttpGet"/>
          <add name="HttpPost"/>
        </protocols>
      </webServices>
    </system.web>
  </location>
...
</configuration>

Note that the _layouts virtual directory is available as a subfolder of every SharePoint Web site. So if you want to limit the use of the web service by only one SharePoint Web site, specify the path like someapp/_layouts/Services/Products.asmx.

PS Here is a good article about how to create a custom web service in SharePoint 2010.