Adding multiple backgrounds with jQuery

I'm trying to do an accordion with jQuery. When you mouseover, it is supposed to change color to orange but also keep the background image. The same thing on mouseleave, but I can't get it on. How do I add the multiple backgrounds with jQuery?

This is the code I am using:

$(".wrap-faq").on("mouseover", hoverFaq);

function hoverFaq() {
  $(this).css("background", "#f7941e");
  $(this).css("backgroundImage", "url(...img/bkg_leer_artic.png) center repeat");
}

$(".wrap-faq").on("mouseleave", unHoverFaq);

function unHoverFaq() {
  $(this).css("background", "#e0e0e0");
  $(this).css("backgroundImage", "url(...img/bkg_leer_artic.png) center repeat");
} 

I am also trying to add an active class when you click on the button, so it keeps orange, but this doesn't work either.

jQuery:

$(".wrap-faq ").on("click", accordion);
function accordion() {
  if (!$(this).hasClass("active")) {
    $(".wrap-faq ").next().slideUp();
    $(this).next().slideToggle();
    $(".wrap-faq ").removeClass("active");
    $(this).addClass("active");
  }
}

CSS:

.active {
background:#f7941e url("../img/bkg_leer_artic.png") center repeat;
}

.wrap-faq {
background:#e0e0e0 url("../img/bkg_leer_artic.png") center repeat;
margin-bottom:2px;
cursor:pointer;
}

Here is my JSFiddle: http://jsfiddle.net/xtatanx/3zvgY/5/

Upvotes: 0

Views: 988

Answers (3)

Town
Town

Reputation: 14906

I'm struggling a bit to understand exactly what you're trying to do, but I think you're wanting to change the background colour whilst still retaining the background image.

This fiddle shows how I'd do it (apologies for the image - actually, I don't apologise for the image, SuperDog rules). http://jsfiddle.net/Town/MtFa4/

You're using background, which is a shortcut for all of the background- CSS declarations, therefore when you do

$(this).css("background", "#e0e0e0");

You're overwriting the background-image declaration.

Upvotes: 0

dezman
dezman

Reputation: 19388

Fiddle

To keep the orange, you needed to add !important to your rule to override the inline mouseout style:

.faq.active {
    background: #f7941e !important; 
}

As far as the background-images go, you need to put them on some photo-hosting site and then refer to their link from that hosting site on the jsFiddle, so that we can see them there.

Upvotes: 1

Plummer
Plummer

Reputation: 6698

I see a lot of people manipulating elements with .css(). This can be frustrating and difficult to troubleshoot since all those change are applied to inline style.

Instead, try using toggleClass(), .addClass() and .removeClass(). Then your styles are defined in a format that's much more organized and easier to manipulate, rather than adding multiple .css() functions. And since you already have those styles pre-defined in your CSS, I don't see why you would use .css() anyway.

Upvotes: 0

Related Questions