Tiago Pina Tiago Pina - 5 months ago 33
CSS Question

Change div background with jquery not working

i have a div that i want to change the background-image. on my code it will change when the page is loaded if a parameter is changed. i wrote a sample code on this jsfiddle:

https://jsfiddle.net/08ovv0r4/

As you can see, when i press the button, the div background is changed but on my code the background image just doesn't load, just change to a white background.
css of div on my code:

div[data-role="page"]{
min-height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
border: 0px;
background-image:url('../img/blue_background.jpg');
}


the line of code where i change the background:

$('div[data-role="page"]').css('background-image','url("../img/green.jpg")');


the new image is on img file inside my www file. there is no problem to the code to load the initial image on the css but when i change it, doesn't load. already tried many answers of some questions here on stackoverflow but none of them resolved.
Any help?

Answer

Code is perfectly okay. Please note that Whenever you are trying to add CSS using jQuery, the CSS code added to the element on the page directly. So in this case, you should use the path considering the HTML (or View) file whenever you are trying to add any CSS based URL in your HTML using jQuery. Above example showing the image path in your CSS file is

background-image:url('../img/<AN IMAGE FILE>');

which is same as the path in jQuery

$('div[data-role="page"]').css('background-image','url("../img/<AN IMAGE FILE>")');

And this is what you are dong wrong. Please correct your image path in your jQuery code considering the HTML file.

Comments