2

I have the below jquery statement

$(this).('span.section1').css('background','url("images/accordion_closed_left.png") no-repeat scroll 0 0 transparent');

How do I write a if else statement for the css condition. What I mean is if the background image is accordion_closed_left.png then <do this> or else <do this>.

just to be precise <do this> are blocks of statement.

Thanks for your time.

2
  • This is going to be slow and horrendous to maintian. Use classes instead. Commented May 23, 2011 at 23:24
  • This is surely not correct: $(this).('span.section1') Commented May 23, 2011 at 23:57

3 Answers 3

8

I'd recommend to use a css class instead and then call jQuery's .hasClass() method on it:

css:

.closed {
    background: url("images/accordion_closed_left.png") no-repeat scroll 0 0 transparent;
}

js:

var $target = $(this).find('span.section1');

if( $target.hasClass( 'closed' ) ) {
    $target.removeClass( 'closed' );
} 
else {
    $target.addClass( 'closed' );
}
Sign up to request clarification or add additional context in comments.

4 Comments

+1! This is by far the most elegant solution. Classes combine styling and state.
a bit more elegant: $(this).find("span.section1").toggleClass("closed");
@roberkules: pretty much depends on the usecase. By just toggling classes you have no chance to do other stuff, which is probably what you want when using it as state.
right. toggleClass would only be used if no extra logic is needed.
0

How to write this in jQuery with 'guides' as a class name....

<script type="text/javascript" >
function guideMenu()
{
    if (document.getElementById('guides').style.display == "none") {
        document.getElementById('guides').style.display = "block";
    }
    else {
        document.getElementById('guides').style.display = "none";
    }
}
</script>

Comments

-1

To naively answer your question:

if ($(this).('span.section1').css('background').match('|/accordion_closed_left\.png"|')) {

}
else {

}

However I support jAndy's answer, .hasClass() is the way to go!

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.