Determine where an element belongs in a jQuery selection

jQuery By . Updated October 29, 2013

Using jQuery to find a specific element in a selection is straightforward — probably one of the earliest things most of us used jQuery to help with, whether using :first, :last, :eq(), or maybe :odd/:even.

However, sometimes you need to be able to do the opposite and find where a given element fits within a given selection. In other words, you might want to ask jQuery whether or not something is :first or :odd, and doing that is a bit less obvious than the other way around.
Click here to read the rest of this post »

Using jQuery to POST [FromBody] parameters to Web API

jQuery, Web API By . Posted April 3, 2013

square-peg-round-holeASP.NET Web API has been one of my favorite recent additions to ASP.NET. Whether you prefer a RESTful approach or something more RPC-oriented, Web API will do just about anything you need. Even if you’re still using ASP.NET WebForms, Web API still has you covered – a nice example of the “One ASP.NET” philosophy that’s finally beginning to come together.

However, ASP.NET Web API throws an unintuitive curveball at you when you want to accept simple primitive types as parameters to POST methods. Figuring this issue out is particularly confusing because it’s one of the rare parts of Web API that violates the principle of least astonishment.

Because of that, using jQuery to interact with those methods requires a slight contortion that seems strange at first, but makes sense once you understand why it’s necessary. In this post, I’ll briefly describe the underlying issue and show you how jQuery can be convinced to work around the issue.
Click here to read the rest of this post »

The crucial .0 in Google CDN references to jQuery 1.x.0

jQuery, Performance By . Updated August 21, 2012

jQuery 1.8 is out, and that new version is available on the Google CDN now.

That’s good news on both counts, but reminds me of an issue that I’ve been meaning to write about for quite a while now. Unfortunately, each new 1.n jQuery release results in a new wave of sites linking to the Google CDN’s copy of jQuery in a way that seems intuitively correct, but results in needlessly poor performance.

If you don’t care about the hows and whys, the short story is that it’s crucial that you always specify the full major.minor.patch version number when you use the Google CDN. Even though jQuery itself only refers to its new releases with a major.minor version number (e.g. 1.8), it’s important that you append a trailing .0 when you use the CDN to include a new minor revision on your page.

In other words, please use this URL to reference jQuery 1.8 on the Google CDN:

ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js

Under no circumstance should you omit that seemingly superfluous .0 in the version number on a production site. Failure to include the trailing zero will result in significantly degraded caching.

If you don’t care about why, you can stop here. Just be sure to add the .0 when you’re referencing jQuery 1.7, 1.8, 1.9, 2.0, 2.1, and so on. If you’re interested in why it’s so important, keep reading.
Click here to read the rest of this post »

Cheerio: A faster, Windows-friendly alternative to jsdom

jQuery, Node.js By . Posted May 23, 2012

When it comes to extracting data from an HTML document on the server-side, Node.js is a fantastic option. Not so much because of any particular feature of Node itself, but because running JavaScript on the server also means that you can run jQuery on the server. Then, many of the techniques you’ve learned on the client-side are applicable on the server-side as well.

Typically, using jQuery on the server with Node is accomplished via a handy module called jsdom. Unfortunately, later versions of jsdom took a dependency on a module called contextify, and that choice has made jsdom not-so-friendly to those of us running Node.exe on Windows.

As I was jumping through the hoops to build contextify in Visual Studio, copy that binary back into my Node.exe project, and cross my fingers, I realized that maybe I’d become too fixated on jsdom as the only solution to this problem. After all, one of Node’s strengths is its thriving ecosystem of third-party libraries (reminiscent of the community that sprang up around jQuery itself several years ago).

Surely, there’s a Windows-friendly alternative to jsdom out there, right?

In this post, I’ll show you why jQuery on the server is useful, the alternative to jsdom that I found (Cheerio), and how to use Cheerio’s jQuery syntax to request and parse a remote HTML document.

Note: You don’t need to be a Windows user to benefit from Cheerio. Though jsdom impressively emulates how a browser might interpret an HTML document, at a much deeper level than most simple HTML parsers, that’s massive overkill in a lot of scenarios. In those simpler situations, jsdom carries a needless performance tax for that highly realistic simulation of the DOM.
Click here to read the rest of this post »

Adding your own callbacks to existing JavaScript functions

JavaScript, jQuery By . Posted January 11, 2012

Hey Dave, is there a way to create an event handler so when .tmpl() is done it will fire a function? I’m trying to make it global, so I was hoping I could say, when ANY template gets done, do this…

The question of how to retroactively add hooks before and/or after a pre-existing JavaScript function executes is one that comes up from time to time. Whether it’s a simple method like tmpl(), a server-generated script artifact, or a function in a third-party script, sometimes it’s desirable to alter a JavaScript function without access to change the original declaration of the function.

One of the handy things about JavaScript is that you can combine its functional and dynamic aspects to make surprisingly quick work of tasks like this one. Doing so is fairly straightforward, but it involves an approach you might not consider if you’re more familiar with languages that lack JavaScript’s unique features.

In this post, I’ll briefly cover a few examples of how to “patch” existing JavaScript functions with callbacks. We’ll begin with simple examples, then address an issue that stems from applying this approach to jQuery plugins, and finish with a more elegant way to handle the problem of patching functions that accept parameters.

Click here to read the rest of this post »

Using CORS to access ASP.NET services across domains

AJAX, ASP.NET, jQuery By . Updated May 9, 2013

Successfully completing a cross-domain request to an ASMX service using CORS

Work on client-side applications long enough and it’s just about inevitable that you’ll eventually want to make an AJAX request that breaches the browser’s XMLHttpRequest security restrictions. Limitations on cross-domain requests are great when they’re preventing malicious sites from malfeasing, but are a thorn in the side when they complicate your legitimate applications.

Traditionally, direct communication across the same-origin boundary required using a rickety (though clever) workaround called JSONP. JSONP is a reasonable compromise if all you need to do is make blind requests to a third-party API like Twitter, but comes up short if you need to use any HTTP verb other than GET. Of course, that’s a deal-breaking issue when you’re working with ASMX ScriptServices or ASPX page methods.

Luckily, a relatively new feature has been making its way into browsers which provides a robust solution to the cross-domain AJAX problem: CORS.

In this post, I’m going to show you how to recognize exactly which requests are cross-origin, how to enable CORS for your ASP.NET site, and the extra configuration necessary when you’re working with ASP.NET’s JSON-enabled services.

Before we get started, I want to emphasize that this approach won’t work with any version of IE prior to IE10. If supporting older versions of IE is a requirement in your target environment, you’re stuck with something like JSONP or a server-side proxy. This will work in any version of IE if Chrome Frame is installed and enabled by your site/server though.

Click here to read the rest of this post »

Help me organize my posts about using jQuery with ASP.NET

ASP.NET, General, jQuery By . Posted November 29, 2011

Image by OZinOH on Flickr

One of the longest running themes here has been the compelling intersection between ASP.NET and jQuery. Beginning with my post about using jQuery to circumvent ASP.NET AJAX’s client-side apparatus for calling ASMX services, I’ve been writing about using ASP.NET and jQuery since the Spring of 2008.

As these related posts have accumulated over the years, I’ve made an effort to weave a thread of cross-links between them posts where appropriate. However, it’s nearly impossible to anticipate every possible entry point and subsequent path that someone might find themselves following here.

So, I’ve decided to finally do what I should have done a year or two ago: Create a top-level index to organize and improve the accessibility of my content for ASP.NET developers interested in integrating jQuery into their sites.

You can see my first draft of that here: jQuery for the ASP.NET Developer

Unlike the other content here, I’m publishing this one long before it’s “finished”. My hope is that I can solicit early feedback to help better construct a useful narrative while the document is still in its formative stages. So, if you have any feedback on the current page or what you think should ultimately be there, please leave me a comment on either this post or that page, contact me directly, or even @mention it my way on Twitter.

Why PhoneGap 1.1.0 broke jQuery Mobile’s back button

jQuery, Mobile, PhoneGap By . Updated May 16, 2013

For the past week, I’ve been neck-deep in a challenging project that combines jQuery Mobile and PhoneGap to do some relatively heavy lifting. Though I’ve used both jQuery Mobile and PhoneGap in the past, this recent exercise left me with a few morsels of newly-hard-earned knowledge. Among that education was learning that PhoneGap 1.1.0 breaks jQuery Mobile’s back button on Android devices.

Being able to use a web-based framework like jQuery Mobile to create a “native” mobile app is one of PhoneGap’s most appealing propositions. So, you can imagine my dismay when wrapping this latest project in PhoneGap broke its navigation. Worse yet, even closing jQuery Mobile’s dialog windows stopped working under PhoneGap 1.1.0.

Luckily, the problem ended up being a minor one with a simple fix. In this post, I’ll briefly show you why PhoneGap 1.1.0 caused jQuery Mobile’s back buttons to stop working and how you can fix that problem in your own app.

Click here to read the rest of this post »

ASP.NET page methods are only as secure as you make them

AJAX, ASP.NET, jQuery By . Posted September 8, 2011

One of the most persistent misconceptions about ASP.NET’s page methods is the notion that they have some intrinsic protection against requests that don’t originate from the page where they’re defined. Since a page method’s code resides within a page’s code-behind file, it’s intuitive to assume that those methods benefit from some form of inherent security.

Unfortunately, that is not the case.

Click here to read the rest of this post »

Use ASP.NET’s HttpHandler to bridge the cross-domain gap

AJAX, ASP.NET, jQuery By . Updated August 5, 2011

When you’re developing client-side applications, a problem you’ll almost inevitably have to deal with is how to work with services that reside outside your website’s domain. Though many modern APIs do support JSONP, which is a clever workaround to somewhat mitigate the cross-domain problem, JSONP has its own problems.

Worse, if you encounter an API with no JSONP support, the cross-domain barrier can quickly become a formidable one. CORS is slowly becoming a viable alternative, but it requires that the remote service support it via special HTTP headers and browser support for CORS is still not ubiquitous.

Until CORS is more broadly supported, an alternative solution is to bounce cross-domain requests through the web server that hosts your website. In ASP.NET, the best tool for implementing that sort of middleman endpoint is the HttpHandler.

In this post, I’ll show you how to create an HttpHandler to service cross-domain requests, how to use jQuery to communicate with the handler, and an example of one improvement that this approach makes possible.

Click here to read the rest of this post »

s