0

I'm trying to execute a function twice, and I can't figure out what I'm doing wrong. JSFiddle here: http://jsfiddle.net/g6PLu/3/

Javascript

function truncate() {
    $(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
}

$('div').each(truncate);

$('.truncate').click(function() {

if ($(this).parent().hasClass('closed')) {
    $(this).parent().removeClass('closed').addClass('open').children().show();
}

else if ($(this).parent().hasClass('open')) {
    $(this).parent().removeClass('open').addClass('closed');
    $('div').each(truncate);
    $(this).show();
}

});

The problem is on line 15, where I call $('div').each(truncate); the second time. For some reason it doesn't seem to be executing. Any ideas?

1
  • It's running every time, but since the div is already visible, show() won't do anything. Commented May 18, 2012 at 22:23

2 Answers 2

2

I think you are overcomplicating a simple task. I'd take advantage of the classes to show/hide stuff with CSS (you're adding the classes but not using them!).

Check out this simpler version:

Relevant CSS

.closed p { display: none; }
.closed p:nth-child(2) { display: block; }

JS

$('div').addClass('closed');
$('.truncate').click(function() {
    $(this).closest('div').toggleClass('closed');
});

http://jsfiddle.net/g6PLu/9/

Sign up to request clarification or add additional context in comments.

1 Comment

Note: nth-child(x) won't work on IE8 and lower. If you need the code to work in older browsers, add a class to the <p> that should always be visible.
1

When you call show, the <p> changes to <p style="display: block; "> that's why, you need to call hide or remove that style part

is this the spected behavior?

else if ($(this).parent().hasClass('open')) {
    $(this).parent().removeClass('open').addClass('closed').children().hide();
    $('div').each(truncate);
    $(this).show();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.