3

I am making a weather app but don't understand why my code doesn't change background image.

Codepen of app: https://codepen.io/Link0w0/pen/ZEeBaOj

Code I added to change background:

<div id="app" :class="typeof weather.main != 'undefined' && weather.main.temp > 16 ? 
    'warm' : ''">
  #app.warm {
  background-image: url('https://images.unsplash.com/photo-1581205135021-fbad89f942a6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2894&q=80')
     background-size: cover;
  background-position: bottom;
}
4
  • 1
    Is weather available when you load the component? If not, it will crash trying to access the property main of undefined, and never change your class. For complex checks like this it is better to take this JS code out of your template and into a computed property that computes the class, you'll have more control that way. Commented May 20, 2021 at 8:01
  • Even removing the logic to <div id="app" class="warm">, it seems the class isn't applied to the tag. Commented May 20, 2021 at 9:29
  • That is strange, it seems even just hard coding the warm class doesn't update the CSS... Commented May 20, 2021 at 10:48
  • That's because the first closing </div> tag is on the wrong position. Take a look at my answer Commented May 20, 2021 at 10:51

2 Answers 2

2

You have several mistakes in your code on codepen:

  1. Change
<div id="app" :class="typeof weather.main != 'undefined' && weather.main.temp > 16 ? 'warm' : ''">

to

<div id="app" :class="weather.main && weather.main.temp > 16 ? 'warm' : ''">
  1. You have a closing </div> directly afterwards the <div id="app" ... snippet. Move this closing tag after the closing </main> tag.

Here ist a working example with a mocked weather object: https://codepen.io/sandmaan/pen/oNZBbYY

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

Comments

0

You can replace the :class logic with below code

<div id="app" :class="{warm: weather.main && weather.main.temp > 16}">
    <!-- rest of code -->
</div>

In the CSS part you can replace #app.warm to .warm

  .warm {
    background-image: url('https://images.unsplash.com/photo-1581205135021-fbad89f942a6?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2894&q=80')
    background-size: cover;
    background-position: bottom;
  }

Comments

Your Answer

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