How to write the code more professional? (duplication in code)

Hello!
I use jQuery.
In the code, there is duplication. But I don’t know how to avoid it. This problem occurs frequently.
Please help.


 //this
    $('#bio h3').click(function () {
        $(this).next().animate({
            'height': 'toggle'
        }, 'slow', 'swing');
    });
    //and this
    $('#bio > div').click(function () {
        $(this).animate({
            'height': 'toggle'
        }, 'slow', 'swing');
    });

Hi there,

Welcome to the forums :slight_smile:

If I was you, I would change your HTML (and CSS) to have a slightly more semantic structure:

<div class="panel">
  <h3>Jony</h3>
  <div>The programmer, play tennis</div>
</div>

Then you can just attach your event handler to the <div class=“panel”>

Fiddle

Also, you can safely discard the $(function(){ … }) callback, as long as you put your JS immediately before your closing </body> tag, as then your DOM will be ready by definition.

HTH

Pullo, thanks you for the helpful answer!:slight_smile:

I’ve updated the code to add { queue: false } options for animation, but now if double-click on the open panel, it closes instantly without animation. I have no ideas how to avoid it.

No problem.

What are you trying to achieve by adding queue: false?
This option determines whether to place the animation in the effects queue. If false, the animation will begin immediately, which is presumably why you are seeing what you are seeing.
http://api.jquery.com/animate/

If you are trying to ensure that the animation completes before responding to the next click you can do this:

$(this).find("div").filter(':not(:animated)').animate({'height': 'toggle'}, 'slow', 'swing');

New fiddle

Reference: http://css-tricks.com/full-jquery-animations/

Yes, this is it!
Thank you!

You’re welcome :slight_smile:

If you are doing a lot with jQuery and animations, make sure you read the article I linked to, as it explains the problem and solution very well.

If you really wan’t to cut down on code you could use something like the following.

$('.panel:not(:first) > div').hide().end().on('click', 'h3', function() {
    var $next = $(this).next();
    
    if ($next.not(':animated')) {
        $next.animate({height: 'toggle'}, 'slow', 'swing');
    }
});

which can also be cut down to

$('.panel:not(:first) > div').hide().end().on('click', 'h3', function() {
    $(this).next().stop(true, true).animate({height: 'toggle'}, 'slow', 'swing');
});