HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Using jQuery UI .position() in a backwards compatible way

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
backwardspositioncompatiblewayjqueryusing

Problem

Trying to implement this API in a way that works pre and post jQuery UI 1.9:

I have a subtle feeling that there should be a more elegant way.

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return n === 0 ? "" :(( n > 0 ) ? ("+" + n) : ("" + n)); 
}

var posOpts = {
    at: "left top",
    of: $target
};

if( isVersionAtLeast($.ui.version, 1, 9) ){
    posOpts.my = "left" + offsetString(markerOffsetX) +
       " top" + offsetString(markerOffsetY);
} else {
    posOpts.my = "left top";
    posOpts.offset = "" + markerOffsetX + " " + markerOffsetY;
}
$dropMarker.position(posOpts);

Solution

Interesting question,

have you tried passing +0 as an offset, that should work and make your code a little easier to read.

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return '' + ( n < 0 ? n : '+' + n );
}


As for the isVersionAtLeast($.ui.version, 1, 9) I would only check this once.

function generateCompatibleOffsetFunction(){

  if( isVersionAtLeast($.ui.version, 1, 9) ){
    return function setOffset( options , offsetX , offsetY ){
      options.my = "left" + offsetString(offsetX ) + " top" + offsetString(offsetY );
    }
  } else {
    return function setOffset( options , offsetX , offsetY ){
      options.my = "left top";
      options.offset = "" + offsetX + " " + offsetY;
    }
  }
}

var setOffset = generateCompatibleOffsetFunction();

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return '' + ( n < 0 ? n : '+' + n );
}

var posOpts = {
    at: "left top",
    of: $target
};

setOffset( posOpts, markerOffsetX, markerOffsetY );

$dropMarker.position(posOpts);

Code Snippets

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return '' + ( n < 0 ? n : '+' + n );
}
function generateCompatibleOffsetFunction(){

  if( isVersionAtLeast($.ui.version, 1, 9) ){
    return function setOffset( options , offsetX , offsetY ){
      options.my = "left" + offsetString(offsetX ) + " top" + offsetString(offsetY );
    }
  } else {
    return function setOffset( options , offsetX , offsetY ){
      options.my = "left top";
      options.offset = "" + offsetX + " " + offsetY;
    }
  }
}

var setOffset = generateCompatibleOffsetFunction();

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return '' + ( n < 0 ? n : '+' + n );
}

var posOpts = {
    at: "left top",
    of: $target
};

setOffset( posOpts, markerOffsetX, markerOffsetY );

$dropMarker.position(posOpts);

Context

StackExchange Code Review Q#27439, answer score: 2

Revisions (0)

No revisions yet.