Wednesday, January 25, 2012

jQuery UI & Disabling Text Selection on Click

Part of making a wonderfully interactive website with jQuery is the process of making certain elements clickable. Sometimes that means making a portion of text interactive without using the regular means of a hyperlink. One problem comes up when doing this, however. When a person clicks rapidly the browser usually interprets this to mean you want to highlight a word or paragraph. How do you stop this? Call .disableSelection() on the element with jQuery. This will disable text selection. For example:
$('#elementId').disableSelection();
It actually binds an event on the object which prevents the default behavior. It is an undocumented feature but it is awfully handy. Remember: it requires jQuery and jQuery UI as it is part of the jQuery UI core.

Friday, January 13, 2012

Synchronous AJAX with JQuery

Yes, you read that right. I just didn't think anyone would understand SJAX.

AJAX, if you don't know, stands for Asynchronous JavaScript and XML and is the term widely applied to sending HTTP POST and GET requests from client-side javascript. In JQuery, that would be $.ajax() or $.getJSON() or any one of the other similar variations.

The question that I had, to continue with the topic of this post, was, How do I do preform a synchronous AJAX call? That is, how would I treat an AJAX call as if it were inline javascript. The JQuery functions I mention above have a parameter where you would specify the call-back function that would run after the requested document is fully retrieved by the client, hence the response and call back are run asynchronously, or whenever the response has been received from the server. Then, how do I make this synchronous so that the code after the call does not execute until the javascript GET or POST is complete.

Well, it is pretty darn easy, I've found. There is a single parameter, "async," that you set to false. That's it. I've written this whole blog post and the answer is a one-word parameter: async.

$.ajax(ajaxurl, {
     async: false
});

So, now you know how to do SJAX. ;)