I’m trying to change the background image of a span using jQuery. Basically I want to keep switching between ‘arrow-down.png’ and ‘arrow-up.png’
The logic is:
- I click on the #profile-li span
- script checks what background image the .arrow-img span has currently got
- if it contains ‘down’ change it to ‘up’
- else change ‘up’ to ‘down’
Up to point 2. it works fine – it goes to the ‘if’ statement, but when I get the alert box the image is still ‘arrow-down.png’. I have no idea what I’m doing wrong here:
$("#profile-li").click(function () {
var bgValue = $("#profile-li").children(".li-title").children(".arrow-img").css('background-image').toString();
if (/down/i.test(bgValue)) {
(bgValue).replace('down', 'up');
alert(bgValue);
}
else
$("#profile-li").children(".li-title").children(".arrow-img").css('background-image').replace('up', 'down');
});
Could someone please help me to find and fix my mistake?
toString()returns a string and not a jquery object so changingbgValue(the string…) has no effect on your page.I would simply add a class with the down-arrow, set the up-arrow as the default background and use jquery’s
toggleClass()method.Something like (I´d need to see the html for an exact solution):