1

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

1
  • 3
    What is jumbotron? Is it an id/class? It probably needs a selector tag (ex. .jumbotron or #jumbotron). Also, you have an extra > on the closing script tag. Commented Sep 8, 2015 at 13:41

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.