Mikey3Strings
Mikey3Strings

Reputation: 109

Switch/Change Background Image of CSS in Jquery using if/else

Been at it for hours Please help

   $("#NewsReel").click(function(){
   if( $(".block_news").css("background","url('/new_skool/images/news_1.jpg')no-repeat"))
   {
   $(".block_news").css("background","url('/new_skool/images/news(2).jpg')no-repeat");
   }
   else
   {
   if( $(".block_news").css("background","url('/new_skool/images/news(2).jpg')no-repeat"))
   {
   $(".block_news").css("background","url('/new_skool/images/news_1.jpg')no-repeat");
   }
   }
   });

Thank You

It changes the image once, but then does not fire the second if statement.

Upvotes: 1

Views: 2641

Answers (4)

Steve Wellens
Steve Wellens

Reputation: 20640

This line/test:

if( $(".block_news").css("background","url('/new_skool/images/news_1.jpg')no-repeat"))

...will ALWAYS return the equivalent of true (it returns a jQuery Object).

Upvotes: 2

andyb
andyb

Reputation: 43823

Getting the background value is not performed this way. You need to use:

if ($('element').css('background') == 'value') {
   ...
}

Also, there is is no guarantee that jQuery will not optimise or set the background exactly the way in which you set it. For example it might return the value as:

no-repeat url('/new_skool/images/news(2).jpg')

It's best to create two CSS classes and just use toggleClass() to change the background image for example in this demo

HTML

<ul id="NewsReel">
    <li class="block_news">news</li>
</ul>​

CSS

li {
   background:url('http://lorempixel.com/25/25/abstract/1/') no-repeat;
}

li.clicked {
    background:url('http://lorempixel.com/25/25/abstract/2/') no-repeat;
}

JavaScript (jQuery)

$("#NewsReel").click(function() {
    $('.block_news').toggleClass('clicked');
    return false;
});

Upvotes: 3

mreq
mreq

Reputation: 6542

Use css classes to style the backgrounds with jQuery addClass / removeClass / hasClass.

Upvotes: 2

trickyzter
trickyzter

Reputation: 1591

In all cases your setting the background. To retrieve the value of the background lose the second parameter in the css method.

Upvotes: 1

Related Questions