Making jQuery Code More Correct/ Efficient -
hey! i've started feeling comfortable using jquery, i'm trying improve write code. there me make code more efficient?
$("a.more_info").toggle(function(){ var itemid = $(this).parent().parent().parent().parent().attr('id'); var itemid_hash = "#" + itemid + " .details_exp"; var itemid_tog_more = "#" + itemid + " a.more_info"; $(itemid_tog_more).addclass("less_info").removeclass("more_info"); $(itemid_hash).fadein(); }, function () { var itemid = $(this).parent().parent().parent().parent().attr('id'); var itemid_hash = "#" + itemid + " .details_exp"; var itemid_tog_less = "#" + itemid + " a.less_info"; $(itemid_tog_less).addclass("more_info").removeclass("less_info"); $(itemid_hash).fadeout(); });
first, there way go 4 levels in dom without stacking .parent() 4 times? second, there better way define "itemid" , " itemid_hash" variables don't have redefine them second half of toggle function? code working great is, want make sure i've doing things in correct way. thanks!
update 2: working demo.
update: completeness, html i'm referring (only relevant part):
<div class="work"> <div class="details"> <nav> <a href="#" class="prev">prev</a> <a href="#" class="more_info">more info</a> <a href="#" class="next">next</a> </nav> <div class="details_exp" style="display: none; "> <!-- content here ---> </div> </div> <!-- ... --> </div>
you can this:
$("a.more_info").toggle(function(){ $(this).addclass("less_info").removeclass("more_info"); // $(this).parent().nextall('.details_exp').fadein() work $(this).closest('.work').find('.details_exp').fadein(); }, function () { $(this).addclass("more_info").removeclass("less_info"); $(this).closest('.work').find('.details_exp').fadeout(); });
there no need build selectors manually. , think item_tog_less
refers clicked element right? can use $(this)
.
if box details comes after link (more precisely parent, looked this) can do:
$(this).parent().nextall('.details_exp').fadein();
reference: find()
, closest()
, nextall()
p.s.: nice site!
Comments
Post a Comment