nkha
nkha

Reputation: 161

Creating conditional statements for JQuery

I have a very novice question, so apologies if the answer to this is obvious.

I am using JQuery to toggle the contents of items based on whether the item has been clicked. I have been able to successfully implement the toggle feature.

I now need to have it load with the first two items set to show() with the rest set to hide(). I have given a unique class name to these first 2 items. I know that I can simply do a $('div.activeitem').show() and then hide thee rest, but I'd prefer to setup a condition.

I am a JQuery novice, so I don't know how to target these elements or their classes in a conditional statement. I've searched google but have been unsuccessful. I want a conditional that asks if the div "newsinfo" also has the class "jopen" then show(), else hide().

Thanks for your help. I have attached my code to help you understand the context of my question:

<script type="text/javascript">
                $(document).ready(function(){
                    // Here is where I'd like to implement a conditional
                    $('div.newsinfo').hide(); // this would be part of my else
                    $('h5.newstoggle').click(function() {
                        $(this).next('div').slideToggle(200);
                        return false;
                    });
                });
</script>

Upvotes: 3

Views: 8048

Answers (5)

Quasipickle
Quasipickle

Reputation: 4498

Just use selectors. For example, if all divs with the class "newsinfo" are visible by default:

$("div.newsinfo:not(.jopen)").hide();

If they're all hidden by default:

$("div.newsinfo.jopen").show();

Upvotes: 1

Chetan S
Chetan S

Reputation: 23813

Why don't you add a default css to jopen class to display: block and the others to display: none ?

something like

 .newsinfo {display: none}
 .jopen {display:block!important}

Upvotes: 1

QuantumRob
QuantumRob

Reputation: 2924

How about simply

$('div.newsinfo').each(function(){
    if($(this).hasClass('jopen')){
       $(this).show()
    }else{
       $(this).hide();
    }
 });

Upvotes: 4

Malfist
Malfist

Reputation: 31805

JQuery has an .hasClass function.

i.e.

if($(".selectableItem").hasClass("selected")){
    //remove selection
    $(".selectableItem").removeClass("selected");
}else{
    //remove the selected class from the currently selected one
    $(".selectableItem .selected").removeClass("selected");
    //add it to this one
    $(".selectableItem").addClass("selected");
}

Upvotes: 1

Skay
Skay

Reputation: 9493

there is hasClass() function. Better way is using toggleClass().

For example:

$('div.blocks').click(function(){
  $(this).toggleClass('class_name');
});

after first click class will be added, after second - removed... and so on ^^

Upvotes: 1

Related Questions