Barney Stinson Barney Stinson - 4 months ago 8
jQuery Question

Changing the background-image

Could you tell me what I have to change here to be able to change the

background-image
via Javascript?



$(document).ready(function(){
$('p').css('background-image', 'url("misc/bilder/2.png")');
});

.p {
height: 100%;
width: 100%;
position: relative;
padding: 25%;
background-size: cover;
background-attachment: fixed;
-webkit-transition: all 0.2s ease;
-moz-transition: all 0.2s ease;
transition: all 0.2s ease;
background-image: url("misc/bilder/1.png");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Some text
</p>





Thanks!

Answer

In your css you're referencing .p which is a class but in your javascript you're referencing p which is the element. This might help:

$(document).ready(function(){ 
    $('.p').css('background-image', 'url("misc/bilder/2.png")');
});

Updated: Question was updated after my answer. Remove the . from .p in css. like so:

css:

p {
    //some css
}

javascript:

$(document).ready(function(){ 
    $('p').css('background-image', 'url("misc/bilder/2.png")');
});

html:

<p>
 some text
</p>