Creating Div Depending On If Character In String Is Text Or White Space - Hang Man Game

Main Document, Full Code:

<!DOCTYPE html>
        <!-- For Mobile Use -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <!-- Open Sans Font -->
        <link href="" rel="stylesheet">

        <!-- Product Sans Font -->
        <link href=',400i,700,700i' rel='stylesheet' type='text/css'>

        <!-- CSS -->
        <link rel="stylesheet" type="text/css" href="/Homepage/Projects/HangMan/style.css">

        <!-- JQuery -->
        <script src="/Resources/jquery-3.1.1.js"></script>

        <!-- Tab Text -->
        <title>HangMan Game - JQuery</title>
        <div class="title">
            <div class="titleName" style="display: block;">Hang Man</div>
        <div class="hanger"></div>
        <div class="word">
            <div class="subject"></div>
            <div class="output"></div>
        <div class="bank"></div>
            $(window).on('load', function() {
                var sports = [
                              "American Football", "Archery", "Badminton", "Baseball", "Basketball", 
                              "Bowls", "Boxing", "Canoeing", "Cricket", "Curling", 
                              "Cycling", "Darts", "Diving", "Fencing", "Football", 
                              "Golf", "Gymnastics", "Handball", "Hockey", "Horse Racing", 
                              "Ice Hockey", "Judo", "Modern Pentathlon", "Netball", "Rowing", 
                              "Rugby", "Sailing", "Shooting", "Snooker", "Squash", 
                              "Swimming", "Table Tennis", "Tennis", "Volleyball", "Weightlifting", 
                var names = [
                             "Prophet Muhammed", "Simon Cowell", "Jennifer Love Hewitt", "The Rock", "Joe Montana", 
                             "Thomas Edison", "Danica Patrick", "Kevin Garnett", "Winston Churchill", "Voltaire", 
                             "Angelina Jolie", "Paul McCartney", "Kate Upton", "Oprah Winfrey", "Dwight Howard", 
                             "Helen Keller", "Katherine Heigl", "Demi Lovato", "Che Guevara", "Pablo Picasso", 
                             "Babe Ruth", "Robert Downey Jr.", "Buddha", "Mark Burnett", "Steve Carell", 
                             "Sandra Bullock", "Matthew McConaughey", "Franklin D. Roosevelt", "Tooby Keith", "Wolfgang Puck", 
                             "Daniel Boone", "Sarah Jessica Parker", "Carl Sagan", "Robin Williams", "Albert Einstein", 
                             "John F. Kennedy", "Phil McGraw", "Frederick Douglass", "Pete Rose", "Elton John", 
                             "Keith Richards", "Jesus Christ", "Morgan Freeman", "Tom Hanks", "Robert De Niro", 
                             "Ray Romano", "Meryl Streep", "William Shakespeare", "Peyton Manning", "Mel Blanc", 
                             "Reese Witherspoon", "Nikola Tesla", "Michael Jordan", "Roald Dahl", "Bob Hope", 
                             "Kenny Chesney", "Courteney Cox", "Kristen Stewart", "Queen Latifah", "George S. Patton", 
                             "George Lucas", "Cameron Diaz", "Scarlett Johansson", "Napoleon Bonaparte", "Amelia Earhart", 
                             "Eddie Murphy", "Larry the Cable Guy", "Manny Pacquiao", "Tom Cruise", "Julius Caesar", 
                             "Oscar Wilde", "Alec Baldwin", "Bruce Springsteen", "James Earl Jones", "Confucius", 
                             "George Washington", "Raoul Wallenberg", "Ulysses S. Grant", "Bill Cosby", "Abraham", 
                             "Liv Tyler", "Thomas Jefferson", "LeBron James", "David Copperfield", "Hunter S. Thompson", 
                             "Fidel Sactro", "Moses", "Danielle Steel", "Jeff Gordon", "John Lennon", 
                             "James Patterson", "Jay Leno", "Tyler Perry", "Johnny Cash", "Neil Armstrong", 
                             "Miley Cyrus", "Eleanor Roosevelt", "Larry David", "Kristen Bell", "Beyonce"
                var jobs = [
                            "Accountant", "Actuary", "Advertising Managers", "Promotions Managers", "Advertising Sales Agent", 
                            "Aircraft Mechanic", "Airline Pilot", "Airport Security Screener", "Airline Reservations Agent", "Air Traffic Controller", 
                            "Architect", "Auto Mechanic", "Bank Teller", "Bartender", "Biological Technician", 
                            "Biomedical Engineer", "Bookkeeping", "Accounting", "Auditing Clerks", 
                            "Brick Mason", "Budget Analyst", "Cardiovascular Technologist", "Cashier", 
                            "Chef", "Chief Executive Officer", "Chemical Technician", "Childcare Worker", "Chiropractor", 
                            "Claims Adjuster", "Appraiser", "Examiner", "Investigator", "Compensation", 
                            "Benefits Manager", "Computer Programmer", "Computer Systems Analyst", "Construction Laborer", "Consultant", 
                            "Cook", "Correctional Officer", "Court Reporter", "Curator", "Customer Service Representative", 
                            "Database Administrator", "Dental Hygienist", "Dentist", "Derrick Operator", "Diagnostic Medical Sonographer", 
                            "Director", "Dietitian", "Doctor", "Editor", "Electrician", "Paramedic", 
                            "Epidemiologist", "Event Planner", "Fashion Designer", "Financial Advisor", "Financial Manager", 
                            "Financial Services Sales", "Firefighter", "Fitness Trainer", "Flight Attendant", "Funeral Director", 
                            "Fundraiser", "Judge", "Glazier", "Grant Writer", "Graphic Designer", 
                            "Guidance Counselor", "Cosmetologist", "Health Educator", "Human Resources Assistant", "Human Resources Manager", 
                            "Home Health Aide", "Housekeeper", "Industrial Designer", "Industrial Production Manager", "Insurance Underwriter", 
                            "Interior Designer", "Interpreter", "Janitor", "Lawyer", "Librarian", 
                            "Library Assistant", "Licensed Practical Nurse", "Loan Officer", "Lodging Manager", "Manicurist", 
                            "Manufacturing Sales Representative", "Market Research Analyst", "Family Therapist", "Massage Therapist", "Mechanical Engineer", 
                            "Medical Assistant", "Medical Laboratory Technician", "Model", "Nurse Practitioner", "Nursing Assistant", 
                            "Occupational Therapist", "Occupational Therapy Assistant", "Painter", "Legal Assistant", "Personal Trainer", 
                            "Pharmacist", "Pharmacy Technician", "Physician Assistant", "Photographer", "Physical Therapist", 
                            "Physical Therapy Assistant", "Plumber", "Police Officer", "Postal Service Worker", "Producer", 
                            "Psychiatric Aide", "Public Relations Specialist", "Purchasing Manager", "Receptionist", "Registered Nurse", 
                            "Retail Salesperson", "Retail Supervisor", "Roofer", "Administrative Assistant", "Security Guard", 
                            "Social Media Manager", "Social Worker", "Software Developer", "Special Education Teacher", "Subway Operator", 
                            "Taxi Driver", "Teacher", "Teacher Assistant", "Technical Writer", "Development Manager", 
                            "Veterinarian", "Waiter", "Web Developer", "Writer"
                var colors = ["Red", "Green", "Blue", "Purple", "Orange", "Light Blue", "Pink", "White", "Black", "Gray", "Brown", "Indigo", "Gold"];

                var rand = Math.floor(Math.random() * 4) + 1;

                if(rand == 1) {
                    var sportsChooser = sports[Math.floor(Math.random() * sports.length)];

                    var count = (sportsChooser).length;
                    for (var i = 0; i < count; i++){

                        if(/\s/g.test(sportsChooser)) {
                            $(".output").append("<div class='wordSpace'></div>");

                            var outputWidth = (50 + 6) * $('.wordSpace').length;
                        }else if(/^[a-zA-Z]+$/.test(sportsChooser)) {
                            $(".output").append("<div class='wordLetter'></div>");

                            var outputWidth = (50 + 6) * $('.wordLetter').length;


                    $(".output").css("width", outputWidth);
                    $(".subject").text("Subject: Sports");
                if(rand == 2) {
                    var namesChooser = names[Math.floor(Math.random() * names.length)];

                    var count = (namesChooser).length;
                    for (var i = 0; i < count; i++){

                        if(/\s/g.test(namesChooser)) {
                            $(".output").append("<div class='wordSpace'></div>");

                            var outputWidth = (50 + 6) * $('.wordSpace').length;
                        }else if(/^[a-zA-Z]+$/.test(namesChooser)) {
                            $(".output").append("<div class='wordLetter'></div>");

                            var outputWidth = (50 + 6) * $('.wordLetter').length;


                    $(".output").css("width", outputWidth);
                    $(".subject").text("Subject: Famous Names");
                if(rand == 3) {
                    var jobsChooser = jobs[Math.floor(Math.random() * jobs.length)];

                    var count = (jobsChooser).length;
                    for (var i = 0; i < count; i++){

                        if(/\s/g.test(jobsChooser)) {
                            $(".output").append("<div class='wordSpace'></div>");

                            var outputWidth = (50 + 6) * $('.wordSpace').length;
                        }else if(/^[a-zA-Z]+$/.test(jobsChooser)) {
                            $(".output").append("<div class='wordLetter'></div>");

                            var outputWidth = (50 + 6) * $('.wordLetter').length;


                    $(".output").css("width", outputWidth);
                    $(".subject").text("Subject: Jobs");
                if(rand == 4) {
                    var colorsChooser = colors[Math.floor(Math.random() * colors.length)];

                    var count = (colorsChooser).length;
                    for (var i = 0; i < count; i++){

                        if(/\s/g.test(colorsChooser)) {
                            $(".output").append("<div class='wordSpace'></div>");

                            var outputWidth = (50 + 6) * $('.wordSpace').length;
                        }else if(/^[a-zA-Z]+$/.test(colorsChooser)) {
                            $(".output").append("<div class='wordLetter'></div>");

                            var outputWidth = (50 + 6) * $('.wordLetter').length;


                    $(".output").css("width", outputWidth);
                    $(".subject").text("Subject: Colors");

Full CSS:

.title {
height: 50px;
width: 100%;
background: #4FC3F7;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
margin: auto;
-webkit-box-shadow: 0px 0px 5px 3px rgba(179,229,252,1);
-moz-box-shadow: 0px 0px 5px 3px rgba(179,229,252,1);
box-shadow: 0px 0px 5px 3px rgba(179,229,252,1);

.titleName {
font-family: 'Product Sans', Arial, sans-serif;
font-size: 28px;
margin: 5px auto;
color: white;
font-weight: 700;
height: 100px;
width: 130px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: default;

.hanger {
height: 500px;
width: 250px;
margin: 60px auto;
background: url(/Homepage/Projects/HangMan/Images/background.svg);
background-size: 100%;
background-repeat: no-repeat;

.word {
height: 50px;
width: 100%;
position: absolute;
top: 650px;
left: 0px;
right: 0px;
margin: 0px auto;

.output {
margin: 0px auto;
height: 50px;

.subject {
height: 40px;
width: 500px;
margin: 0px auto;
text-align: center;
font-family: 'Product Sans', Arial, sans-serif;
font-size: 24px;

.wordLetter {
height: 50px;
width: 50px;
display: inline-block;
margin: 3px;
border-bottom: 2px solid black;
border-radius: 5px;

.wordSpace {
height: 50px;
width: 50px;
display: inline-block;
margin: 3px;
border-bottom: 2px solid white;
border-radius: 5px;
background: green;

Detailed Description:

Q: What Am I Trying To Accomplish?
A: I am trying to make a JQuery hangman game.


Q: What Is The Problem I Have Ran In To?
A: The output is only outputting div that resembles a space if the string has two words. If the string only has one word it works fine.


Q: Whats The Full Function Of The Hang Man Game? [Detailed]
     On window load a image of the hanger is displayed. Also the browser picks randomly using
Math.random() from 1 to 4. There are 4 categories. Names, sports, jobs, and colors. If it picks 1 it is choosing the sports category. If it picks 2 it is choosing the names category. If it picks 3 it is choosing the jobs category. if it picks 4 it is choosing the colors category.
      Once it chooses a category it will then proceed to randomly pick a word / string out of the category.
      Now we have picked a category, and picked a word for the player to guess. We need to count the length of the word / string so we can display the given amount of divs for each letter to be placed in. That's exactly what the variable count does.
      This is where my problem occurs. Once it has counted the length of the word / string it needs to loop through the string and for each letter test whether the character is a letter or a white space. I am assuming the problem is my if statement inside of the for loop statement. But I don't know what I should do to fix it.

Note: This is not the full game. It does not work fully yet.

Screen Shots:
One Word String: Word is: Orange
Multi Word String: Word is: Queen Latifah

The green divs are spaces .wordSpace, and the divs with a rounded border-bottom are the letter divs .wordLetter. They are empty because as the player is guessing the letters if the letter is correct it will place the letter in the div. Also the green div .wordSpace is only green to give you a image of where the spaces are other wise they would be transparent. The spaces are supposed to make it seem as the word / string is two words.

1 answer

  • answered 2017-06-17 19:28 CryptedData

    if(/\s/g.test(colorsChooser.charAt(i)) fixed it. As it focuses on each character and not the full string. Thank you Quagaar