Reputation: 4239
I am trying to simplfy my massive else if statements. Are there better way to get the shorter codes? Most of the conditions are using different css property and the way inserting/appending to the element..
Thanks for the help!
var img = $("<img src='images//anim.gif class='Img'>");
var cssProp = {'position':'absolute',
'z-index':99,
'top': topPos,
'left': leftPos
}
//$element var represent all kinds of elements I have in my DOM
if($element.attr('id')=='count' || $element.attr('id')=='assign' ){
img.prependTo($element)
}else if($element.is('#title')){
cssProp.top=+20;
img.insertBefore($element);
}else if($element.is('#tab')){
detail_img = $("<img src='images/anim.gif' id='tab1' class='Img'>");
detail_img.insertBefore($element.parent());
detail_img.css(cssProp);
}else if($element.is('#tab2')){
detail_img = $("<img src='images/anim.gif' id='tab2' class='Img'>");
detail_img.insertBefore($element.parent());
detail_img.css(cssProp);
}else if ($element.is('#e_btn')){
cssProp.left=+20;
cssProp.top=+3;
img.insertBefore($element);
img.css(cssProp);
}else if($element.is('#date_set')){
img.insertBefore($element);
}else if($element.is('td')){
img.prependTo($element).css(cssProp);
}else if($element.is('#l_title')){
cssProp.top+=10;
img.insertBefore($element);
img.css(cssProp);
}else if($element.is('#status')){
cssProp.top =+10;
img.insertBefore($element).css(cssProp);
}else if($element.is('label')){
img.appendTo($element)
}else if($element.closest('#divTab').length>0){
($element.attr('id')=='work')? cssProp.left+=10 : '';
cssProp.top+=5;
img.insertBefore($element);
img.css(cssProp)
}else{
img.insertBefore($element);
img.css(cssProp)
}
Upvotes: 0
Views: 116
Reputation: 18078
To reduce the number of lines :
if{}
clause down to one line - this is fairly trivial. Where necessary, use $.extend()
to manipulate cssProp
.if
conditions can be composited with ||
.Doing this, I get the if/else chain down from 49 to 21 lines.
To improve runtime efficiency start off with the following statements :
var id = $element.attr('id');
var tag = $element.get(0).tagName;
OK, this adds 2 lines back in
Then, in the if
conditions, perform string comparisons on id
and tag
rather than use jQuery expressions. The only exception is if($element.closest('#divTab').length>0)
, which doesn't follow the same pattern.
Upvotes: 1