The Code
"use strict";
// Controller function
// get the input string value
function getValue() {
// make sure alert msg is not initially visible
document.getElementById('alert').classList.add('invisible');
// get the user input string
let userStr = document.getElementById('userString').value;
// call the reverse function
let reverseStr = reverseString(userStr);
// pass the reversed string to the display function
displayString(reverseStr);
}
// logic function
// reverse the string value
function reverseString(userStr) {
// declare empty array to be populated
let reverseStr = [];
// reverse string with a decrementing for loop
for (let i = userStr.length - 1; i >= 0; i--) {
// concatenate and populate the array with index values
reverseStr += userStr[i];
}
// retrun the reversed string
return reverseStr;
}
// view function
// display the reversed string value back to the page
function displayString(reverseStr) {
// write to the page using a template literal
document.getElementById('msg').innerHTML = `${reverseStr}`;
// turn on inline alert success message
// (remove 'invisible' from the class listings)
document.getElementById('alert').classList.remove('invisible');
}
JS Reverse
Using HTML, JavaScript, custom CSS & Bootstrap to design an application that captures user input and then executes code to reverse that input, displaying the reversed input.
getValue() function
Here we use javascript to set an inline alert message's css class to 'invisible' and to "Get" a user input field value in the HTML file by using document.getElementById to locate the html tags with id's of 'alert' and 'userString'.
reverseString() function
Then we pass the 'userString' array to a logic function that uses a decrementing for loop to move backwards through the index of the string array where each index item is cancatenated and then added to the empty reverseStr = [] array. Once the for loop is complete we return this reversed array back to the getValue() controller function.
displayString() function
From the Controller function we call the view function displayString() passing it the reversed array variable 'reverseStr'. Using getElementbyId and it's innerHTML property we locate the html tag with id of 'msg' and write the reversed string to the page using a template literal. Then we remove the inline 'alert' message's css 'invisible' class to display the reversed string in an inline alert success message.