JS conditionals using dynamic var data

xanis

Lifer
Sep 11, 2005
17,571
8
0
I'm using Weather Underground's API for a personal project. Basically what I'm doing is pulling a location and temperature via jQuery and Ajax. This is the code so far:

Code:
<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">
jQuery(document).ready(function($) {
	$.ajax({
		url: "http://api.wunderground.com/api/c2dc53f77e6d7223/geolookup/conditions/q/PA/Philadelphia.json",
		dataType: "jsonp",
		success: function(parsed_json) {
			var location = parsed_json['location']['city'];
			var temp_f = parsed_json['current_observation']['temp_f'];
			$("#current-temp").text('The temperature in ' + location + ' is ' + temp_f +'F.');
		}
	}); //end ajax call
});
</script>

</head>

<body> 
	<div id="current-temp"> </div>
	<div id="color-test"> </div>
</body
>
</html>

What I now want to do is pull a temperature from the temp_f variable and write a conditional that changes the background color of my "color-test" div based on the result. The problem I'm running into is that temp_f is getting its data from a dynamically-generated JSON file.

How can I grab the temperature number (whatever it is) and put it into a variable that I can use for my conditional?

---
EDIT: Apologies if anything isn't clear; I'm a designer by trade, not a developer. :p
 
Last edited:

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
Well you have it in temp_f. Why not just examine it there and then set the class of the current_temp element accordingly?
 

xanis

Lifer
Sep 11, 2005
17,571
8
0
Well you have it in temp_f. Why not just examine it there and then set the class of the current_temp element accordingly?

I'm an idiot. This is why I don't do front-end development. :p

Worked like a charm:

Code:
jQuery(document).ready(function($) {
	$.ajax({
		url: "http://api.wunderground.com/api/c2dc53f77e6d7223/geolookup/conditions/q/PA/Philadelphia.json",
		dataType: "jsonp",
		success: function(parsed_json) {
			var location = parsed_json['location']['city'];
			var temp_f = parsed_json['current_observation']['temp_f'];
			$("#current-temp").text('The temperature in ' + location + ' is ' + temp_f +'F.');
			  if (temp_f <= '77') {
        $("#color-test").css("backgroundColor","red");
      } //end color change conditional
		}
	}); //end ajax call
});