The Code for TIMETRAVEL
//Get the string from the page
//controller function
function getValue(){
document.getElementById("alert").classList.add("invisible");
let userString = document.getElementById("userString").value;
let revString = reverseString(userString);
displayString(revString);
}
//Reverse the string
//logic function
function reverseString(userString){
let revString = [];
//reverse a string using a for loop
for (let index = userString.length - 1; index >= 0; index--) {
revString += userString[index];
}
return revString;
}
//Display the reversed string to the user
//view function
function displayString(revString){
//Write the message to the page
document.getElementById("msg").innerHTML = `Your string reversed is: ${revString}`;
//Show the alert box
document.getElementById("alert").classList.remove("invisible")
}
//inline script from app.html
document.getElementById("btnSubmit").addEventListener("click",getValue);
The code shown contains all of the Javascript used in this project. Most of the Javascript is contained inside of an external script, site.js. One line of Javascript runs inline inside of app.html. A few key pieces of it are explained below.
getValue
getValue is a function that is triggered when the "Reverse Me" button is clicked on the app webpage. (See the bottom of the Javascript.)
It first makes the "alert" element invisible to the user, (which it will then make visible later once the string has been reversed.)
It then declares userString equal to the value of whatever the user input is into the input area on app.html.
It then passes userString into a new declared revString which will be passed to displayString and also our next function.
reverseString
reverseString declares the variable called revString equal to an empty string.
Then, a for loop is created which uses the information from the user input given to us by the variable userString. It firsts calculates the length of userString and subtracts 1 from that integer. We subtract 1 so that we can get the integer of the last index of the string the user inputted.
The for loop loops and decrements by 1 through the string as long as it gets an index greater than or equal to 0. Each time it loops, it concatenates the character of the index to the revString. When it gets to an index that below 0, the loop ends and the variable revString is returned.
displayString
displayString takes the information from revString and uses it in a template literal to write a message to the element using the "msg" id.
It then removes the "invisible" class from the element with the "alert" id. The reversed string is now shown!