ToddN
ToddN

Reputation: 2961

JQuery hide Class if other class is visible or shown

Found similar questions but nothing that covers exactly what I need. I kept it simple in my example and I want to use JQuery.

I have two classes. I want to hide the "filter" div if the "category" div is shown on page load. There are currently NO styles associated with either class. I believe I am pretty close but it doesn't work.

<script language="text/javascript">
if(!$(this).hasClass("category")){
$('filter').css('display', 'none');
}
</script>

<div class="category">By Category</div>
<div class="filter">By Custom Filter</div>

Thanks in advance!

Upvotes: 2

Views: 20505

Answers (5)

ten5peed
ten5peed

Reputation: 15890

Use .length to test if an element is present.

Use .hide() & .show() to show and hide elements.

And finally, you want the code to run only when the page has finished loading, so you want to wrap it all in $(document).ready().

So something like this should work best:

<script language="text/javascript">
    $(document).ready(function() {
        //following code will hide all elements with a class of 'filter'
        //if any elements with a class of 'category' are found
        if($('.category').length){
            $('.filter').hide();
        }
    });
</script>

<div class="category">By Category</div>
<div class="filter">By Custom Filter</div>

HTHs,
Charles

Upvotes: 4

Robin Maben
Robin Maben

Reputation: 23054

 <div class="category">By Category</div>
 <div class="filter">By Custom Filter</div>

Assuming by "shown on page load" you mean rendered and not the show/hide visibility.

$('.category').each(function(){
    $('.filter').hide();
});

Upvotes: 0

tinifni
tinifni

Reputation: 2392

jQuery

$('div').each(function() {
    if ($(this).hasClass("category")) {
        $('.filter').css('display', 'none');
    }
});

or just:

if ($('.category').length) {
    $('.filter').css('display', 'none');
}

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185933

var $filter = $(".filter");
var $category = $(".category");

$category.is(":visible") ? $filter.hide() : $filter.show();

Upvotes: 2

CD..
CD..

Reputation: 74126

Change the selector to $('.filter')

Upvotes: 2

Related Questions