1

I'm new to jQuery but I am already incredibly impressed with its power. Here's my question:

I want to

  • add class='dec' to #jf1 when I click it if it has class='undec'
  • add class='undec' to #jf1 when I click it if it has class='dec'

Here's what I have - it isn't working!

<script>
$(document).ready(function(){
$(function() {

    $('#jf1').click(function() {

        if ('#jf1'.hasClass("undec")) {
            $('#jf1').toggleClass("undec dec");
    }
        else if ('#jf1'.hasClass("dec")) {
            $('#jf1').toggleClass("dec undec";
    }

    });

});
});
</script>
1
  • 1
    why you use $(document) and $(function) both together ? Commented Feb 26, 2013 at 8:12

2 Answers 2

6

There are several syntax errors in your code, your if statement should be:

if ( $('#jf1').hasClass("undec") ) {

Also $(function(){}) is shorthand version of $(document).ready(function(){}), you should not nest them. toggleClass removes and adds classes, so there is no need to use if statement here.

$(function() {
    $('#jf1').click(function() {
        // `this` refers to the clicked element
        $(this).toggleClass("undec dec");
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks for the quick response. I agree that .toggleClass is perfect for this - but I wanted to use an if/else statement because when I click the item, I also want to .show or .hide an element based on its CSS class, based on whether or not the "filter" has class='dec' or class='undec'
0

try this: http://jsfiddle.net/YS5F5/

 $(document).ready(function () {
    $('#jf1').click(function () {
        alert("hello");
        $('#jf1').toggleClass("undec");
        $('#jf1').toggleClass("dec");

    });
});

dont need the function again after the jQuery(document).ready portion

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.