So, I have this div in my HTML called ‘G36C’, I also have a CSS class called ‘#G36C’, so the style is applied to the div, okay?
Now, I want to change the background image in the CSS style by using JS, but I cant seem to get it to work, below is the JS I’m using:
function weaponOrganiser(){
alert("weapon test");
var weaponOrg = "Vector";
//G36C
if(weaponOrg == "G36C"){
//$("#G36C").css('background-image', 'url("' + images/weapons/G36C/G36C.png + '")');
$('#G36C').css('background-image', 'url("/images/weapons/G36C/G36C.png")');
alert("G36C applied");
}
else if(weaponOrg == "Vector"){
//$("#G36C").css('background-image', 'url("' + images/weapons/Vector/Vector.png + '")');
$('#G36C').css('background-image', 'url("/images/weapons/Vector/Vector.png")');
alert("Vector applied");
}
}
So, all I’m doing is checking if weaponOrg = G36C, then change the CSS background to G36C.png, else if weaponOrg = Vector, then change the background to vector.
Now, When I run the code, I only get the alert(“weapon test”) to show … the rest of the alerts don’t show, which suggests to me that the if statements aren’t working …?
This is speculation because your code looks like it should work (assuming the images are where you say they are), but, are you sure
weaponOrganiser()is fired after theG36Celement is loaded in the DOM? Because that is the only way (in my limited tests) I could make it fail.If you’re using jQuery that would mean (a basic fix of) wrapping whatever calls
weaponOrganiserin a$(...)call.If you’re not using jQuery hopefuly this will help anyway, but I don’t want to post an example for regular javascript, because while my jQuery is rusty, my real javascript has already sheared off and fallen by the wayside a few miles back. 🙂