Forums
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › How do i make this Jquery code shorter and more efficient?
@Jarolin, @jamy_za’s way of writing that code is EXACTLY what you need.
@Merri, i know, all it takes are a couple classes and some transitions and boom goes the dynamite. It’s just the way the OP wants it.
Thank you for the pen. It definitely works perfectly. Thanks.
Actually when i add a new member card the animation doesn’t happen to that newly added member div. What must i do when adding or when removing member divs?
@Jarolin, are they dynamic or load with ajax?
@JohnMotyLJr dynamic
As you can see [Here](http://codepen.io/unasAquila/pen/zbkgx) it should not matter how many you add.
@unasAquila Here i added one more which is the last one and see what happens http://reallycoolstuff.net/PROJECTS/Unica/#
Its getting the same id as the previous one.
@unasAquila *FACEPALM!. Feel like an idiot.
How about instead listening to the parent object?
$(‘#team_members_group’).on(‘mouseenter mouseleave’, ‘[id^=”staff_member_”]’, function(e) {
var topValue = (e.type === ‘mouseenter’) ? ‘-160px’ : ‘0px’;
$(
‘#’ + this.id.replace(‘staff_member_’, ‘staff_member_info_’)
).stop().animate({top: topValue}, 200);
});
Can add or remove on the fly and things will always work.
@jamy_za
I understand what you’re saying, and in general, I agree; especially if it is a matter of project coding standards or conventions in a team.
However, conventions and understandability don’t need to (and shouldn’t) stand in the way of efficiency. In this case, `this` is already a DOM element. Creating a new jQuery object is expensive and unnecessary. Two preferable alternatives:
… change the convention. Conventions should be about coding style, and stay away from specific logic. Yes, if you’re doing something, it’s nice for everyone to do it the same way. That doesn’t mean you should be doing anything you wouldn’t have any reason to do otherwise.
… comment your code. Then you know *for sure* everyone will understand what you’re doing.
/* same result as $( this ).attr( ‘id’ ); faster */
var el_id = this.id;