-4

Was reading some jquery code form here. What does the + sign and spaces do in "url(" + imageUrl + ")" ?

I m new to jquery and js.

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Setting background-image CSS Property</title>
<style>
    .box{
        width: 500px;
        height: 300px;
        border: 5px solid #333;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Set background image of a div on click of the button
    $("button").click(function(){
        var imageUrl = "images/sky.jpg";
        $(".box").css("background-image", "url(" + imageUrl + ")");
    });    
});
</script>
</head>
<body>
    <div class="box"></div>
    <p><button type="button">Set Background Image</button></p>
</body>
</html><!DOCTYPE html>
mic
  • 155
  • 2
  • 9

2 Answers2

1

In Javascript, you can concatenate strings by using the + sign.

For example,

let string1 = Hello;
let string2 = World;
let fullString = string1 + string2; // This is now: HelloWorld.

So basically your code is just appending the imageUrl to the url().

In the end you will have something like url("images/sky.jpg");

Alessandro
  • 164
  • 1
  • 2
  • 11
1

The plus (+) operator has several usages in JavaScript. The actual action that the plus operator does is defined by the context in which the operator is located.

In a numerical context this operator is used for addition

1 + 2 // 3

In a string context it's used for concatenation
'1' + '2' // '12'
1 + '2' // '12'

yunzen
  • 32,854
  • 11
  • 73
  • 106