Design and code a program which prompts a user for the year they were born, calculates the user's age and displays the user's age. If the user's age is over 40 then set the background color of the web page to red. The solution must use the JavaScript Date object and use programmer created functions for calculating the user's age.
pretty small problem i just need to make the screen turn red if age is more then 40 I just cant seem to make that happen...
<html>
<head>
<title> Age of person </title>
<div id="age"></div>
<body>
<script>
function determine_age_of_person ( year )
{
var today = new Date();
var now_year = today.getFullYear();
var age = now_year - year_person_was_born;
return age;
}
var year_person_was_born;
//unsure about below statement the '==' part
var age_of_person==age;
do
{
year_person_was_born = prompt("Enter year you were born", "");
year_person_was_born = parseInt (year_person_was_born1 );
}
while (is(year_person_was_born));
age_of_person = determine_age_of_person ( year_person_was_born );
if (age_of_person>40)
document.body.style.backgroundColor = "red";
else
document.body.style.backgroundColor = "white";
document.getElementById("age").innerHTML = "You are " + age_of_person + " years old";
</script>
</body>
</html>
Ok there are lot of code placement issues here (you have an html element outside of the body element, return statements outside of functions, function arguments that you don't use). Here is a simplified version of what you are building (demo)
<html>
<head>
<title> Age of person </title>
</head>
<body>
<div id="age"></div>
<script>
function determine_age_of_person (year) {
return (new Date()).getFullYear() - year;
}
var age_of_person = determine_age_of_person(parseInt (prompt("Enter year you were born", ""), 10));
if (age_of_person>40) {
document.body.style.backgroundColor = "red";
} else {
document.body.style.backgroundColor = "white";
}
document.getElementById("age").innerHTML = "You are " + age_of_person + " years old";
</script>
</body>
</html>
Here is breakdown of the changes I made:
Moved <div id="age"></div> inside the body
Used argument year in determine_age_of_person() instead of global variable
Combined prompt, parseInt and determine_age_of_person into one line (and added a radix to parseInt, because JavaScript has weird rules related to non base 10 numbers, it's a good habit to get into)
Added curly braces to if statement
Removed useless code like do() and while()
change
if (year_person_was_born > 40)
to
if (age_of_person > 40)
Related
I'm wanting to setup a while loop in heading 1 that allows a user to input three employees names with hours worked, hourly wage, and total pay. The loop needs to calculate those, account for overtime (over 40 hours receives 1.5x pay for any hours over 40), and display all three employees information after calculating.
What do I need to fix with my code to achieve the desired result?
I've referred to W3Schools and Youtube on "Creating a while loop" and "Declaring variables".
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta charset="ISO-8859-1">
<title>JavaScript Page</title>
<script language="javascript">
"<h1> Martha's Diner</h1>"
// Variables get declared
var employeeCount; employeeCount = "3";
var hoursWorked; hoursWorked = " ";
var hourlyWage; hourlyWage = " ";
var notOvertime; notOvertime = "<=40";
var overTime; Overtime = ">40";
var totalPay; totalPay = "overTime + notOvertime";
var employeeName = " ";
var i = 0;
/// While Loop
while (i < employeeCount) {
employeeName = window.prompt ("Enter an Employee Name");
hoursWorked = window.prompt ("Enter Hours Worked");
hourlyWage = window.prompt ("Enter Hourly Wage");
if (hoursWorked <= 40)
hourlyWage * hoursWorked;
i++
}
</script>
</head>
<body>
</body>
</html>
I expected the loop to end and calculate keyed information, but the loop doesn't stop or calculate at all.
you are running an infinite while loop as any positive integer in java or javascript takes as true and check your closing loop braces.To input three values using while you can try like this:
var a=0;
while(a<3)
{
//your codes
//your codes
a=a+1;
}
this will execute 3 times
I want to append the given string to the textarea i have, i want to append the text in the way it should look like someone typing on the texture,because i have the voice playing in the background for 6 seconds which which says the same thing to be written.
<textarea id='typeable' style='font-size:18px;background:#F8E71C'></textarea>
<script>
function addText(event) {
document.getElementById("typeable").value += "Hello welcome to the new world of javascript"
}
</script>
how can i do this
Count the number of characters in the sentence, and then calculate the time for each char by dividing the total time with the no. of characters and then call the time Interval and run it until all the characters are printed.
Still you can decide the time taken to print each character and modify it as per your need. Please note that the time is taken in milliseconds.
var chars = "Hello welcome to the new world of javascript".split("");
var textarea = document.querySelector('textarea');
var total_time=6000;
var index = 0;
var time_per_char = total_time/chars.length;
var t = setInterval(function(){
textarea.value += chars[index];
index++;
if (index === chars.length){
clearInterval(t);
}
},time_per_char);
<textarea style="width:100%;background:#E1ECF4">
</textarea>
Code is attached below:
<!DOCTYPE html>
<html>
<script>
function appendText() {
document.getElementById("typeable").value= document.getElementById("typeable").value + "Hello welcome to the new world of javascript";
}
</script>
<body onload="appendText()">
<textarea id='typeable' style='font-size:18px;background:#F8E71C'></textarea>
</body>
</html>
Write the JavaScript to read the number of hours worked from the user. Then write the JavaScript to calculate how much money the user made if they were paid $12/hour for the first 40 hours worked, and $18/hr for all hours worked over 40. Then use the alert() function to print the total amount to the user.
what code do I have to use
var y = prompt("Enter a Value","");
Lol #OverComplicated. The answer is there just remake a better version and try your homework before being spoonfed.
var BarryScott = {
PricePerHour: 12,
HoursWorkedByBarry: 0,
PrintPayment: function() {
if ( this.HoursWorkedByBarry > 40) {
var RemainHours = this.HoursWorkedByBarry - 40;
alert(this.PricePerHour * 40 + RemainHours * 18);
} else {
alert(this.PricePerHour * this.HoursWorkedByBarry);
}
},
AskHoursFromBarry: function() {
this.HoursWorkedByBarry = prompt("Enter Hours you worked");
this.PrintPayment();
}
}
BarryScott.AskHoursFromBarry();
Create a folder and place your index.html and javascript code inside.
Run index.html .
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Im lazy to do my assignment</title>
<script src = "billhours.js"></script>
</head>
<body>
</body>
</html>
billhours.js
var getInput = prompt("Enter Number of Hours worked");
var first40hrs = billHours(40, 12);
var over40hrs = billHours(getInput - 40, 18);
var totalSalary = first40hrs + over40hrs;
alert("Total Salary is "+totalSalary);
function billHours(hours, rate){
return hours*rate;
}
//This function only works for hours 40 and above.
//It's your job to put conditional statements if hours is below 40. Keep Coding.
The website is supposed to display a message counting down to the tax day. I can't seem to get anything to display on the page. The scrollbar doesn't even show up with the color even though I put in the write code. Some advice please.
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8">
<title>TaxDay</title>
<script type="text/javascript">
<!-- Hide from old browsers
function scrollColor() {
styleObject=document.getElementsByTagName('html')[0].style
styleObject.scrollbarFaceColor="#857040"
styleObject.scrollbarTrackColor="#f4efe9"
}
function countDown() {
var today = new Date()
var day of week = today.toLocaleString()
dayLocate = dayofweek.indexOf(" ")
weekDay = dayofweek.substring(0, dayLocate)
newDay = dayofweek.substring(dayLocate)
dateLocate = newday.indexOf(",")
monthDate = newDay.substring(0, dateLocate+1)}
yearLocate = dayofweek.indexOf("2016")
year = dayofweek.substr(yearLocate, 4)
var taxDate = new Date ("April 16, 2017")
var daysToGo = taxDate.getTime()-today.getTime()
var daysToTaxDate = Math.ceil(daysToGo/(1000*60*60*24))
function taxmessage() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
taxDay.innerHTML = "<p style='font-size:12pt; font-
family:helvetica;'>Today is "+weekDay+" "+monthDate+" "+year+".
You have "+daysToTaxDate+" days to file your taxes.</p>"
}
}
//-->
</script>
The <div> id is taxDay if it's relevant. The body onLoad event handlers are scrollColor(); countDown(); and taxmessage().
you are not closing the countdown() function before the taxmessage() function - meaning that taxmessage is nested within countdown(). Also you do not have semicolons ";" after each line of the js. You should rewrite the code to either include the function of taxmessage() or close out countdown() first and call taxmessage with arguments passed to get the date variables.
check your console for errors
I have searched for an answer, but I haven't found a answer that address my issue, as I'm not how to word it as a search. My problem is that I want to use the same JS code for multiple HTML files, but only a few values need to be changed in the JS depending on the HTML file.
HTML
<!DOCTYPE html>
<!--Replace:: Line 14, Line 82: 'PROJECT' with name of the project; Line 15: '0' with the last counted image; line 94: 'PROJECT' with base name of picture files-->
<!--fill in any special instructions at each step in the text array.-->
<html>
<head>
<link type="text/css" rel="stylesheet" href="../defaultStyle.css"/>
<script type="text/javascript" src = "../buttons.js">
var num = 0
var NAME = PROJECT
var LAST = 100
var LAST1 = LAST-1
text[0] = "a"
text[1] = "b"
<!--...etc-->
</script>
<link type="text/css" rel="stylesheet" href="../projectStyle.css"/>
</head>
<body>
<div>
<p href="JavaScript:StepDisplay()" id="Step">PROJECT</p>
</div>
<div id="Text">
</div>
<div>
<button type="button" onClick="JavaScript:Back()"> Back</button>
<button type="button" onClick="JavaScript:Next()"> Next</button>
</div>
<div>
<img src="image/PROJECT (0).jpg" id="Pic">
</div>
</body>
</html>
***JavaScript***
var text = new Array[100]
var num = 0
var NAME = PROJECT
var LAST = 100
var LAST1 = 99
function Next(){
num = num + 1
if (num == LAST)
{num = 0}
stepnum = num.toString();
document.getElementById("Pic").src = "image/"+ NAME + "(" + stepnum + ").jpg"
document.getElementById("Text").innerHTML = text[num]
if (num == 0)
document.getElementById("Step").innerHTML = NAME
if (num == 1)
document.getElementById("Step").innerHTML = "Pieces"
if (num > 1)
document.getElementById("Step").innerHTML = "Step " + (num-1).toString();
}
function Back(){
num = num - 1
if (num < 0)
{num = LAST1}
stepnum = num.toString();
document.getElementById("Pic").src = "image/" + NAME + "(" + stepnum + ").jpg"
document.getElementById("Text").innerHTML = text[num]
if (num == 0)
document.getElementById("Step").innerHTML = NAME
if (num == 1)
document.getElementById("Step").innerHTML = "Pieces"
if (num > 1)
document.getElementById("Step").innerHTML = "Step " + (num-1).toString();
}
You should define your local variables before including the script.
<script>
// local variables
var firstname = "John", lastname = "Doe";
</script>
<script src="hellohello.js"></script>
In the js file, we need to make sure our local variables exists, if it doesn't we can define default variables or stop the script.
// Check if the variable already exists
// If it doesn't we'll give it a default variable
if(typeof(firstname)==='undefined') firstname = "Guest";
if(typeof(lastname)==='undefined') lastname = "";
alert("Hello "+ firstname +" "+ lastname);
// Or just do something else
if(typeof(firstname)!=='undefined' && typeof(lastname)!=='undefined') {
// Do something
} else {
// Do nothing
}
Demo 1: http://bycreativeminds.com/playground/vanilla/js-demo-110.html
Demo 2: http://bycreativeminds.com/playground/vanilla/js-demo-111.html
I don't know if this is better then hutchbat's or not, but it is a different way.
What I did was break up buttons.js into two files: buttons_init.js and buttons.js
buttons_init.js includes all the intialization, but not the code that uses it
var text = new Array[100]
var num = 0
var NAME = PROJECT
var LAST = 100
var LAST1 = 99
So in your HTML, you do this (preferably at the buttom unless you need it to run early):
<script type="text/javascript" src = "../buttons_init.js">
<script>
// overwrite any variables you need to change
num = 5
LAST = 200
LAST1 = LAST-1
</script>
<script src = "../buttons.js>
The advantage of this is that you don't have to remember to check to see a variable is undefined in your buttons_init.js. The disadvantage is that you have two files to include (which slows down the load slightly, although not as much as it used to) and you have to remember to put default variables you want people to override in the _init file (which has the side affect of documenting it). Some people will prefer one way, some will prefer the other. I'm just presenting it as an alternative.
A completely different way would be to send an "options" structure into the Next and Prev functions (merging them with default values inside the functions), or make them into a class (or jQuery plugin), but that seems overkill for such a simple example.