mardi 22 novembre 2016

How to change the background-image using jQuery and if, else if, and else statements

Disclaimer, total beginner. Just started learning at the very end of October!

My current project is creating a local weather app on codepen. My API I got from openweathermap.org and I'm using

 $.getJSON("http://ip-api.com/json",function(data2){
    lat = data2.lat;
    long = data2.lon; 

to get the users location.

My goal is to have a different background image load based on the weather description from openweathermap.org. This i've given the var weatherType... I'm using if, if else, else statement to go through the different weatherTypes and assign a background image based on the weatherType that matches with the output. Also, all of my img's i got from unsplash. Great resource!

ex... if the weatherType is rainy, I want to have a background photo of rain.

Here is an example of my code:

if (weatherType = "clear sky" || "few clouds" || "calm" || "light breeze" || 
"fresh breeze"){
    $('body').css('background-image', 'url(http://ift.tt/2gc2aZP 
    1476611338391-6f395a0ebc7b?ixlib=rb-0.3.5&q=80&fm=jpg&crop= entropy&cs= 
    tinysrgb&s=e444d875e55debddc2319c386d96df90 )');
}

 else if (weatherType = "light intensity drizzle" || "drizzle   " || "heavy
 intensity drizzle" || "light intensity drizzle rain" || "drizzle rain" || 
 "heavy intensity drizzle rain" || "shower rain and drizzle" || "heavy shower 
 rain and drizzle" || "shower drizzle" || "light rain" || "moderate rain" ||
 "heavy intensity rain" || "very heavy rain" || "extreme rain" ||  "light
 intensity shower rain" || "shower rain" || "heavy intensity shower rain" ||
 "ragged shower rain" ){
    $("body").css("background-image",
    "url(http://ift.tt/2gxwu5B
    -0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&s=c11591dd2cf9 c9d41b1d577df 
    052785)");
 }

My problem is the images don't seem to load, and instead I get this random photo instead, and that doesn't even always show up. I have also not focused on css or any form of style, as I'm trying to get this done first.

you can go to my codepen to look at the whole code: http://ift.tt/2gbYwzl

Really appreciate the help!

Best,

Forrest

Aucun commentaire:

Enregistrer un commentaire