using if/else statement in html - javascript

I am new to building websites, so can anyone please help me?
I want to use an if/else statement in html to display text and some movies on my website. Below I have added my html code, but it sees the if/else statement as a text and not as a code. How can I get this if/else statement to work, using the temperature output from my js code with openweather API?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css">
<link rel="stylesheet" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type='text/javascript' src='app.js'></script>
</head>
<body>
<input type="text" value="In which city are you?" id="city">
<button id="search">Submit</button>
<p id="demo"></p>
<p>The weather outside is: </p>
<div class= "weather">
Fill in your location first
</div>
<p>What will you be making for dinner tonight?</p>
<div class="inspiration">
Give me some inspiration!
<div class="recipe">
if (Math.round(data.main.temp) == null) {
<p>Fill in your location first</p>
} else {
if (Math.round(data.main.temp) < -5) {
<p> Oh man.. It is way too cold! Stay inside the whole day and have a nice and hot turkey soup. Make sure you don’t freeze </p>
<iframe width="392" height="220" src="https://www.youtube.com/embed/SdJfxGo5PQM?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
} else if (Math.round(data.main.temp) === -5 - 5){
<p>wow look at that weather, it is quite cold.. With those temperatures a chicken and fries curry would be nice don’t you think? </p>
<iframe width="392" height="220" src="https://www.youtube.com/embed/PfoOxeTXdXA?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
} else if (Math.round(data.main.temp) === 5 - 15) {
<p> Today is a good day, don’t you think? Some cheeseburger cups would taste great!</p>
<iframe width="392" height="220" src="https://www.youtube.com/embed/k-2KdH6k0nA?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
} else if (Math.round(data.main.temp) === 15 - 25) {
<p> With those temperatures it is not a bad idea to have a BBQ! Here is a recipe for hummus to have as a side dish!</p>
<iframe width="4392" height="220" src="https://www.youtube.com/embed/XN4aSh-Dj4Y?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
} else if (Math.round(data.main.temp) === 25-35) {
<p> Damn it's hot! I can hardly think of anything to have for dinner to cool down. </p>
<p> Just go get some ice cream please. </p>
} else {
<p>Those temperatures are insane! Are you in a sauna?</p>
}
}
</div>
</div>
</div>
</body>
</html>
this is my js code
$(document).ready(function(){
$('#search').click(function(){
var city = $('#city').val();
console.log(city);
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=9334f947893792dcb9b2e2c05ae23eb0", function( data ) {
$('.weather').html(Math.round(data.main.temp)+ ' degrees Celcius');
});
});
});

JavaScript code needs to be defined inside <script> tags otherwise it won’t work.
Just put this code in the same function below your jQuery code. And create an empty <div> tag with any ID in place of the <p> and <iframe> then populate them with jQuery. Then depending on your condition change its innerHTML (using the jQuery function html()). Example:
$(document).ready(function()
{
$('#search').click(function()
{
var city = $('#city').val();
console.log(city);
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=9334f947893792dcb9b2e2c05ae23eb0", function( data )
{
$('.weather').html(Math.round(data.main.temp)+ ' degrees Celcius');
});
});
if (Math.round(data.main.temp) < -5)
{
$("#YOU_CHOSEN_ID").html("<p> Oh man.. It is way too cold! Stay inside the whole day and have a nice and hot turkey soup. Make sure you don’t freeze </p>
<iframe width='392' height='220' src='https://www.youtube.com/embed/SdJfxGo5PQM?rel=0&showinfo=0' frameborder='0' allowfullscreen></iframe>")
}
});
I used one condition. Add the rest like I did with this one.
If you’re still facing problems let me know so I can help you.

Related

How can I insert a variable in iframe src to reach felixibilty for open the various sites? (by: html page and javascript )

I want my users to open their desired sites from my website, for this manner I need to insert a variable in src of iframe which change by user input strings.
Indeed I need a type of code like bellow:
<html>
<body>
<script type="text/javascript">
var userInput_stringVariable= "this part is user desired input string" ;
var adress= "https://en.wikipedia.org/wiki/" + userInput_stringVariable ;
</script>
<iframe src=adress width="100%" height="100%" frameborder="0"></iframe>
</body>
</html>
This code doesn't work, while I need a code like this to work with!
A textfield where user can enter whatever they would like to search on wikipedia or whatever website you want, a submit button which will call a function after it is clicked. answer.value will give the value of textfield and it's concatenated with website initial url.
HTML
<input type="text" name="inputField" id="answer" placeholder="Enter what you wanna search">
<button type="button" name="button" onclick="mySubmit()">Submit</button>
<iframe id="search" src="" width="100%" height="100%" frameborder="0"></iframe>
Script
<script>
function mySubmit() {
let getInput = answer.value;
var address;
address = "https://en.wikipedia.org/wiki/" + getInput;
document.getElementById('search').src = address;
}
</script>
Here is a function that will probably do what you want:
<script type="text/javascript">
function selectPage() {
var userImput_stringVariable = prompt("desired imput string");
if (userImput_stringVariable != null) {
document.getElementById("getPage").innerHTML =
"<iframe width='100%' height='100%' src='https://en.wikipedia.org/wiki/" + userImput_stringVariable + "'></iframe>";
}
}
</script>
Just add
<body onload="selectPage()">
somewhere in the body so the function runs when the page does.
It'll open a prompt, the user then has to enter the address.
Also you'll need this in the body too:
<p id="getPage"></p>
It creates a paragraph with the contents of the iframe within the fuction.

Error handling in a Javascript search function

this is actually a follow up question to this question
that was solved thanks to Rory McCrossan.
I now have this functioning script; a search function that shows a div depending on a searchword.
JS
$('#search').click(function() {
var txt = $('#search-criteria').val();
if (txt)
$('.fruit').hide().filter('#' + txt.toLowerCase()).show();
});
CSS
.fruit {
display: none;
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>
What I now wonder is if someone could help me with some kind of error handling to add to this script, preferably that can be smoothly added without rewriting the logic of the script. I.e. I'd like to display another div with a message when the search comes up with no result and/or when the user makes an empty string search.
Since I'm actually an UX designer my technical skills are somewhat limited and I'm therefore very grateful if someone could help me with this...
Thanks in advance!
simple javascipt error handing using try and catch:--
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function adddlert2($a){
alert($a);
}
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
You can use try and catch in this case, but If you want to be informed about all irregularities in your application I prefer to use dedicated services for this job.
I use Sentry.io, this is nice service to handle exceptions and errors in backend and frontend. Is simple to use, you only need to add one additional JS script without modifying existing code. More about installation process here
I guess what you're looking for is this :) I know changing to .keyup() had nothing to do with your question, so change it back if you like
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div id="default" class="fruit">
no fruit found
</div>
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>
and
<script>
$(document).ready(function(){
$('#search-criteria').keyup(function() {
var txt = $('#search-criteria').val();
if (txt){
var elements = $('.fruit').hide().filter('#' + txt.toLowerCase());
if(elements.length > 0){
elements.show();
}
else{
$("#default").html("No result found for "+txt);
$("#default").show();
setTimeout(function(){
$("#default").hide();
}, 1000);
}
}
});
});
</script>
Another error handing(javascript example) using javascript SEARCH function:--
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
var str_wrong = "Visit";
var n = str.search("Visit");
document.getElementById("demo").innerHTML = n;
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>

Using counter/index to cycle through an array of images onclick

I am trying to create code that goes through a traffic light sequence when I click the button. I know there are a lot of people having the same problem however none of the solutions they got seem to work - I can only get the first asset (red traffic light) to display on the webpage and when I click the button nothing happens... Maybe I just need my code proof reading and there is something really obvious I've made a mistake on?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3</h1>
<img id="image" src="red.png" style="width:200px">
<input type="button" onclick="nextpic()" value="change image" >
<script>
var image = document.getElementById("image");
var counter = 0;
var trafficlights = [
"redamber.png",
"amber.png",
"green.png",
"red.png"
];
function nextpic(){
counter =counter+1;
if (counter == trafficlights.length){
counter = 0;
}
image.src = trafficlights[counter];
}
</script>
</body>
</html>

use html5 output tag to display javascript variables?

Sorry if this is a silly question, but I've been trying to use AJAX to display my javascript variables in 'real time' with little luck. I'm definitely a beginner though so this could be the problem haha- When I see the AJAX code, it always seems to require an additional url that it refreshes, but I just want to refresh the javascript variables on click.
http://jsfiddle.net/bagelpirate/m9Pm2/
<script>
var one = 0;
var two = 0;
var three = 0;
</script>
<body>
<div id="div_1">
One: <script>document.write(one)</script> |
Two: <script>document.write(two)</script> |
Three: <script>document.write(three)</script>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" onclick="one++;" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" onclick="two++;" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" onclick="three++;" />
</div>
</body>
As you can see in the above code, when a user clicks one of the images, I want to increment the count and display it at the top of the page. I found the HTML5 output tag, and was wondering if it's possible to use this to display the javascript variable in real time? Everything I've read seems to imply it can't be done because the output tag only works on forms? Anyway, I figured it couldn't hurt to ask!
Thanks for your time!
You shouldn't use document.write to write to the DOM after it's finished loading. You have tagged your question with jQuery, so I'll assume you can use that to update things. Instead, update the DOM from within your script block. Here is an example that might help you get started.
http://jsfiddle.net/prxBb/
<script type="text/javascript">
$(function() {
var one = 0;
var two = 0;
var three = 0;
$('img#mine').click(function() {
one++;
$('span#one').html(one);
});
$('img#forest').click(function() {
two++;
$('span#two').html(two);
});
$('img#farm').click(function() {
three++;
$('span#three').html(three);
});
});
</script>
<body>
<div id="div_1">
One: <span id="one"></span> |
Two: <span id="two"></span> |
Three: <span id="three"></span>
</div>
<div id="div_2">
<img id="mine" src="https://si0.twimg.com/profile_images/3170725828/ac1d6621fc3c3ecaa541d8073d4421cc.jpeg" />
<img id="forest" src="http://blogs.dallasobserver.com/sportatorium/No.%202.png" />
<img id="farm" src="https://si0.twimg.com/profile_images/3732261215/bd041d1f0948b6ea0493f90507d67ef2.png" />
</div>
</body>
Maybe you should try putting all your variables inside a named object, iterating through it at predefined interval and displaying the values.
var varContainer = {
one:0,
two:0,
three:0
};
jQuery("#div_2 img").on('click',function(){
jQuery.each(varContainer,function(key,value){
//Add key + value to the DOM
if(jQuery("."+key+value).length<1)
jQuery("#div_2").append("<div class='"+key+value+"'></div>");
var newHtmlVal= "<p><span>Var name: "+key+"</span><br><span>Value: "+value+"</span>";
jQuery("."+key+value).html();
});
});
HTML
<div id="div_2">
</div>
Of course the script could be upgraded to look through each variable recursivley in case of nested objects/arrays...
Hope this helps!

How to tell a javascript function what element to manipulate?

I am so very new to asp.net and javascript, and I am supposed to do the following task in a couple of days. I know I have to learn all the basics, before asking, but really don't know where to get what I need in short time. Thanks a lot in advance!
Here's a number cities, which will be shown on a country map:
Each city has it's own style (since city positions are different), defined in a css.
<div class="node">
<div class="taxonomy">
</div>
<div class="content">
<div id="contact_map" runat="server">
<ul>
<li id="city1" onmouseover= "onmouseoveragent(this)"
onmouseout="onmouseoutagent(this)">
<a href="someAddress"><span class="hideme">Some City Name</span>
</a>
<p class="hideme">Some City Name<strong class="tel">0123456789</strong>
</p>
</li>
<%-- other cities here, with different city name and tel --%>
</ul>
</div>
</div>
</div>
I will probably try to figure out how to create these city items dynamically later.
Below is a hint box, to be shown when mouse is over the city. It has to be repeated for all the cities. (Question1: How can I create these hint boxes dynamically, and somehow fill them with the information associated with the right city? Maybe I have to create the previous list dynamically, too..)
<div id="agentVisit" class="floating-tip-wrapper" style="margin: 0px; padding: 0px; position:
absolute; display:none; opacity: 1;">
<div class="floating-tip" style="margin: 0px;">Some City Name
<strong class="tel">0123456789</strong>
</div>
</div>
And this is tha javascript code for onmouseover and onmouseout of each city:
(Question 2: How can I tell the function which agentVisit to get? )
<script language="javascript" type="text/javascript">
function onmouseoveragent(e) {
var hint = document.getElementById("agentVisit");
console.log(hint);
hint.style.display = 'block';
hint.style.top = Math.max(e.offsetTop - hint.offsetHeight, 0) + "px";
hint.style.left = e.offsetLeft + "px";
};
function onmouseoutagent(e) {
var hint = document.getElementById("agentVisit");
hint.style.display = 'none';
}
</script>
I would appreciate it if you provide an idea (or just a general hint) of how to do it. Or just a link to a quick tutorial. Thanks!
I think you are making this way more complicated than it has to be, because you can leverage data dash (data-) attributes of DOM elements and then use something like jQueryUI Tooltip.

Categories

Resources