2

I am trying to find out how to show/hide an element depending on the fact whether the element ".question a" has the class "checked" or not. But it isn't working. Anybody knows why ;( ?

$().ready(function() {

    var myLink = ".question a";
    if (myLink.hasClass('checked')) { 
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }   

});
2
  • 1
    var myLink = $(".question a"); Commented Aug 19, 2013 at 6:32
  • how many questions will be there in a page Commented Aug 19, 2013 at 6:33

4 Answers 4

4

Try like

$(document).ready(function() {
    var myLink = $(".question a");
    if (myLink.hasClass('checked')) { //You can also use $(this).hasClass
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }   
});

If you want to change the status of link then call the same while your event triggered like

$(myLink).on('click',function(){
    if ($(this).hasClass('checked')) { 
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it's partially working. The problem is that now it's hidden as default and it doesn't reflect the state of the link class. In firebug I see that it's changing from to class="checked" to nothing (and back again depending how many times I clicked) when clicking on it. But the .answer is always hidden. Any idea why? Btw. I have only on .question aelement(link)
Then you need to check the class when you are changing the state of link class also
0

Try

$(function() {

    var myLink = $(".question a"); // need to use jQuery selector here
    if (myLink.hasClass('checked')) { 
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }   

});

Comments

0

Repalce

var myLink = ".question a";

With

var myLink = $(".question a");

Comments

0

add $ before myLink

$(document).ready(function() {

    var myLink = ".question a";
    if ($(myLink).hasClass('checked')) { 
        $('.answer').show(300);
    }
    else {
        $('.answer').hide(300);
    }   

});

2 Comments

Thanks, the problem is that it's always hidden now ;( even though the class is changing from "checked" to nothing.
write example in jsfiddle.net

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.