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

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

    $('#bio h3').click(function () {
            'height': 'toggle'
        }, 'slow', 'swing');
    //and this
    $('#bio > div').click(function () {
            '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">
  <div>The programmer, play tennis</div>

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


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.


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.

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


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');