Reputation:
Good day.
HTML
<div id="Button"></div>
CSS
background: url("../images/play.png") left center no-repeat;
background-size: cover;
width: 100px;
height: 100px;
float: left;
cursor: pointer;
JQuery
$("#Button").on("click",function() {
$(this).css("background", 'url("../images/pause.png") left center no-repeat;');
});
But unfortunately, the background doesn't change. Why doesnt it?
Upvotes: 2
Views: 345
Reputation: 123739
Your issue is with the semicolumn in the end of the property value. remove it and try.
EX:
$(this).css("background", 'url("http://placehold.it/32x32") left center no-repeat');
presence of semi-column while specifying the value for the css property name makes it invalid and it doesn't get applied.
$(this).css("background", 'url("../images/pause.png") left center no-repeat;');
^___ Here
Also do note that applying css directly to the element makes it more difficult for cascading the styles and less maintainable, since they are applied directly on to the style property of the element. Best way to go is to add a css rule and set the class to the element.
Upvotes: 3
Reputation: 3167
The issue may have been incorrect image paths or the semicolon in the css (adding a semicolon will make it not work). I have created a jsfiddle the demonstrates the solution to your problem, although with alternate images since I don't have access to your originals.
The relevant js code is reproduced below:
$("#Button").on("click", function(){
$(this).css('background', 'url(../images/pause.png) left center no-repeat');
})
Upvotes: 0
Reputation: 1978
This is more efficient way and you seperate your code
HTML
<div id="Button"></div>
CSS
background: url("../images/play.png") left center no-repeat;
background-size: cover;
width: 100px;
height: 100px;
float: left;
cursor: pointer;
div with Class bg
div.bg {
background: url("../images/pause.png") left center no-repeat;
}
JQuery
$("#Button").on("click",function() {
$(this).addClass("bg");
});
Upvotes: 1
Reputation: 2289
Try this:
$("#Button").on("click", function () {
$(this).css({
'background-image': 'url("../images/pause.png")',
'background-position': 'left center',
'background-repeat': 'no-repeat'
});
});
As Bergi and André Dion mentioned in the comments, you can remove the background-position
and background-repeat
properties if they don't need to change when the background image does.
Upvotes: 0
Reputation: 8781
Try to set each property separately. Also you should check that url is correct.
Upvotes: 0