Reputation: 583
I have this script embedded on the index page of my site:
$(document).ready(function(){
$(".bgtoggle").click(function () {
$(".metro").toggleClass("bgcolorchange");
});
});
The CSS classes the script refers to look like this:
.bgcolorchange {
background-image: url("../images/mthc/imageN.jpg");
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
overflow : hidden ;
margin:0;
padding:0;
z-index:3;
}
.metro {
background-image: url("../images/mthc/music-therapy-image1.jpg");
z-index : 2;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
overflow : hidden ;
margin:0;
padding:0;
}
In a different script file includes this code for handling button clicks:
$('.fa-question-circle').parent().on('click', function () {
$(".metro").css('background-image','url('+"../images/mthc/image2.jpg"+')');
I have tested the first script for the background change to happen and this works fine. However when I try to use the script for my "fa-question-circle" button, the change of image doesn't happen and the bgtoggle also doesn't work.
Any suggestions why it no longer functions?
Upvotes: 0
Views: 62
Reputation: 32202
The problem comes from the difference in relative paths depending on where that path is specified. When specified in a CSS file, the path is relative to that file. When you assign a url()
path to an element in JavaScript, it is relative to the page in which the script is executing.
I'm guessing that your stylesheets are stored in a subfolder, so go to the parent before descending into the images folder. Whereas your JavaScript is probably running in a page that is already in the parent folder, so it doesn't need to "go up one folder" before descending into the images folder.
Upvotes: 1