When writing a new jQuery plugin is there a straightforward way of checking that the current version of jQuery is above a certain number? Displaying a warning or logging an
Here is a check I used to make sure the user was using at least v. 1.3.2 of jQuery.
if (/1\.(0|1|2|3)\.(0|1)/.test($.fn.jquery)
|| /^1.1/.test($.fn.jquery)
|| /^1.2/.test($.fn.jquery))
{
//Tell user they need to upgrade.
}
I'm surprised no one has given this solution yet:
//Returns < 0 if version1 is less than version2; > 0 if version1 is greater than version2, and 0 if they are equal.
var compareVersions = function (version1, version2){
if(version1 == version2)return 0;
var version1Parts = version1.split('.');
var numVersion1Parts = version1Parts.length;
var version2Parts = version2.split('.');
var numVersion2Parts = version2Parts.length;
for(var i = 0; i < numVersion1Parts && i < numVersion2Parts; i++){
var version1Part = parseInt(version1Parts[i], 10);
var version2Part = parseInt(version2Parts[i], 10);
if(version1Part > version2Part){
return 1;
}
else if(version1Part < version2Part){
return -1;
}
}
return numVersion1Parts < numVersion2Parts ? -1 : 1;
}
What about:
function minVersion(version) {
var $vrs = window.jQuery.fn.jquery.split('.'),
min = version.split('.'),
prevs=[];
for (var i=0, len=$vrs.length; i<len; i++) {
console.log($vrs[i], min[i], prevs[i-1]);
if (min[i] && $vrs[i] < min[i]) {
if (!prevs[i-1] || prevs[i-1] == 0)
return false;
} else {
if ($vrs[i] > min[i])
prevs[i] = 1;
else
prevs[i] = 0;
}
}
return true;
}
I wrote that code on my forked gist: https://gist.github.com/budiadiono/7954617, original code written by dshaw on: https://gist.github.com/dshaw/652870.
Found this in jquery.1.3.2 source:
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
.....
// The current version of jQuery being used
jquery: "1.3.2",
I didn't check, but something like "$.fn.jQuery" might work.
Pass version as array of integers, like jQmin([1,4,2])
to check if the current version is equal or above v1.4.2.
function jQmin(min) {
var i, cur,
cver = $.fn.jquery,
c = cver.split(".");
while (min.length < c.length) min.push(0);
for (i = 0; i < min.length; i++) {
cur = parseInt(c[i]);
if (cur > min[i]) return true;
if (cur < min[i]) return false;
}
return (cver === min.join("."));
}
If it's enough to check minor version, not patch version, you can do something like
parseFloat(jQuery.fn.jquery) >= 1.9
It is possible to change this slightly to check >= 1.4.3:
parseFloat(jQuery.fn.jquery) > 1.4 ||
parseFloat(jQuery.fn.jQuery) == 1.4 && parseFloat(jQuery.fn.jQuery.slice(2)) >= 4.3