...

View Full Version : problem changing div background image



ocejamusic
09-29-2011, 06:25 PM
Hello all,

I want to set dynamically a div's background image when the page loads, so I have my code like so:

javascript code:

window.onload = init;

function init(){
$(document).ready(function(){
$('#button1').css('background', 'url(../imagenes/buttonNormal.jpg)');
$('#pg1').css('color', 'black');
$('#pg1').css('font-weight', 'normal');
});
}

My CSS stylesheet is like so:

#buttonsWrapper {
position:relative;
margin 50px 0px 0px 0px;
}

.buttons {
text-decoration:none;
font-family:Verdana, Geneva, sans-serif;
font-size:17px;
font-weight:bold;
color:#FFF;
}

#button1 { margin: 31px 0px 0px 0px; }
#button2 { margin: -43px 0px 0px 195px; }
#button3 { margin: -43px 0px 0px 390px; }
#button4 { margin: -43px 0px 0px 585px; }
#button5 { margin: -43px 0px 0px 780px; }

#button1, #button2, #button3, #button4, #button5 {
width:172px;
height:33px; /* 33px */
padding-top:10px;
text-align:center;
}

#button1:hover, #button2:hover, #button3:hover, #button4:hover, #button5:hover {
background-image:url(../imagenes/buttonNormal.jpg);
background-repeat:no-repeat;
background-position:top;
}

My HTML sourcecode is like so:

<div id="buttonsWrapper">
<div id="button1"><a href="#" id="pg1" class="buttons">link1</a></div>
<div id="button2"><a href="#" id="pg2" class="buttons">link2</a></div>
<div id="button3"><a href="#" id="pg3" class="buttons">link3</a></div>
<div id="button4"><a href="#" id="pg4" class="buttons">link4</a></div>
<div id="button5"><a href="#" id="pg5" class="buttons">link5</a></div>
</div>

The thing is that the background image that I'm calling (../imagenes/buttonNormal.jpg) is not loading for some reason... what am I doing wrong?

Thank you so much in advance...

DanInMa
09-29-2011, 06:37 PM
1. your css rule and the jquery css rule are the same. if you arent not seeing the image at all then the problem most likely lies in the url you are using.


2. you have written your jquery in a document.ready block so you dont have to call it on window onload. it should look like this:

window.onload = init;



$(document).ready(function(){
$('#button1').css('background', 'url(../imagenes/buttonNormal.jpg)');
$('#pg1').css('color', 'black');
$('#pg1').css('font-weight', 'normal');
});


or this if you so desire:


function init(){
$('#button1').css('background', 'url(../imagenes/buttonNormal.jpg)');
$('#pg1').css('color', 'black');
$('#pg1').css('font-weight', 'normal');
}

window.onload = init;

DanInMa
09-29-2011, 06:39 PM
oh also it should be


$('#button1').css("background-image", "url(../imagenes/buttonNormal.jpg)")



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum