Reputation: 13
Hi and hope you can help. My JavaScript isn't that hot and I have tried searching but had no luck with find the correct method.
I am trying to add css background-image to a div (.jumbotron) but dynamically change the url depending on the screen size. The image will be picked up from https://unsplash.it where the url can be coded to the dimensions required i.e. https://unsplash.it/200/300
<script type="text/javascript">
function setBackground () {
$('jumbotron').css('background-image', 'url(https://unsplash.it/' + $(window).height(); + '/' + $(window).width();')');
}
</script>
I hope this make sense and thanks in advance
Upvotes: 1
Views: 1488
Reputation: 9583
Assuming jumbotron
is an id or class, make sure you give it a selector tag.
You can do something like this to achieve what you are wanting: JS Fiddle
function setBackground() {
var height = $(window).height();
var width = $(window).width();
$('.jumbotron').css('background-image', 'url(https://unsplash.it/' + width + '/' + height + ')');
}
Notes on your original:
jumbotron
needed a selector tag (class/id)
$(window).width();
was missing a +
after it.
For the Upslash link, the width needs to be before height to work properly.
One more note:
Do you want this function to run on load? If so, be sure to call that function since its not set to run instantly.
Upvotes: 2
Reputation: 71
Try This:-
<script type="text/javascript">
function setBackground () {
$('jumbotron').css('background-image', 'url(https://unsplash.it/' + $(window).height(); + '/' + $(window).width(); + ')');
}
</script>>
you have missed the '+' sign after width.
Upvotes: 0
Reputation: 576
Try removing the semi colon in the string.
function setBackground () {
$('jumbotron').css('background-image', 'url(https://unsplash.it/' + $(window).height() + '/' + $(window).width()')');
}
Having a semicolon in the middle of the string will force it to stop before the string is completed.
Upvotes: 0