Niels
Niels

Reputation: 25

jQuery .detach / append in if/else statement

I'm having a bit a trouble with creating a category filter for my custom post type taxonomy, I've tried allot of different things in jQuery and I think this should be the best way to get what I want.

Code:

var divs;

$('.category').on('click', function() {
    if(divs == 1) {
        alert('ayylmao?');
        $('section#showcase').append(detached);
        divs = 0;
    } else {
        divs = 1;
        var lolxd = $(this).find('a').attr('id');
        alert(lolxd);
        var detached = $('section#showcase').contents().not("." + lolxd).detach(); 
    }
});

It has been a while ago that I used jQuery but for some reason the var 'detached' wont append to the section showcase.

Would like to hear what I am doing wrong ;_;

Upvotes: 0

Views: 241

Answers (1)

intentionally-left-nil
intentionally-left-nil

Reputation: 8306

detached is declared within your click handler function. That means it's re-created every time the function runs.

Contrast that to your use of divs which is declared outside the function and thus persists across function calls.

There are many ways to solve this, but the simplest would be to follow the same pattern that you have for divs and have code that looks like this:

var divs;
var detached;
$('.category').on('click', function() {
    if(divs == 1) {
        alert('ayylmao?');
        $('section#showcase').append(detached);
        divs = 0;
    } else {
        divs = 1;
        var lolxd = $(this).find('a').attr('id');
        alert(lolxd);
        detached = $('section#showcase').contents().not("." + lolxd).detach(); 
    }
});

Speaking more generally, it sounds like when you detach a showcase, you want to keep it around so you can add it back later. Depending on the makeup of your program, it might be more useful to just change the display of that item to none. However, this does change the semantics if you had multiple things you could append to your showcase.

Upvotes: 1

Related Questions