mchandleraz
mchandleraz

Reputation: 381

jQuery .click() not firing as expecting

What I'm trying to achieve is:

Here's a Fiddle

jQuery(document).ready(function($) {
    $('.question h4').click(function () {
        $(this).parents('.question').css('height', '90');
        $(this).siblings('p').css('margin-top', '0');
        $(this).parent().addClass('open');
    });

    $('.question.open h4').click(function () {
        $(this).parent.removeClass('open');
        $(this).parents('.question').css('height', '65px');
        $(this).siblings('p').css('margin-top', '35px');
    });
});

Upvotes: 0

Views: 102

Answers (3)

Pointy
Pointy

Reputation: 413682

You really just need one handler:

$('.question h4').click(function () {
    if ($(this).is('.open h4')) {
        $(this).parent.removeClass('open');
        $(this).parents('.question').css('height', '65px');
        $(this).siblings('p').css('margin-top', '35px');
    }
    else {
        $(this).parents('.question').css('height', '90');
        $(this).siblings('p').css('margin-top', '0');
        $(this).parent().addClass('open');
    }
});

Your second handler assignment does nothing because none of your <h4> elements start off with the "open" class (or, at least, I suspect they don't).

Upvotes: 1

Michael
Michael

Reputation: 2165

As Pointy mentioned, you only need 1 handler with a conditional statement. Also, for speed, overhead, and simplicity, I would consider stringing all desired action on a node into one line (i.e., anything you want to do with a $(this).parent() should be stringed together so jQuery only has to parse the DOM one time).

$('.question h4').click(function () {
    if (!$(this).parent().hasClass('open')){
        $(this).parents('.question').css('height', '90').addClass('open');
        $(this).siblings('p').css('margin-top','0');
    }else{
        //$(this).parents('.question').css('height', '65px');
        $(this).parent().css('height', '65px').removeClass('open');
        $(this).siblings('p').css('margin-top', '35px');
    }
});

Upvotes: 2

km6zla
km6zla

Reputation: 4877

Your first click handler is firing even if .question is .open. You need to exclude .open from the first selector.

$('.question:not(.open) h4').click(...

Upvotes: 4

Related Questions