views:

191

answers:

5

Hi folks,

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>
+1  A: 

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 ^^

Skay
+1  A: 

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");
}
Malfist
+1  A: 

How about simply

$('div.newsinfo').each(function(){
    if($(this).hasClass('jopen')){
       $(this).show()
    }else{
       $(this).hide();
    }
 });
Mech Software
+1  A: 

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}
Chetan Sastry
it's not necessary use `!important` in this case couz .jopen notation goes later ;-)
Skay
True. I just added it to emphasize jopen should override newsinfo.
Chetan Sastry
+1  A: 

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();

Pickle