Words within a string are divided in the center, with JS and CSS involved

I'm currently working on developing a hangman game in JavaScript (I am new to web technologies) and I have come across my first challenge. The placeholder string for the word to be guessed, which consists of hyphens and spaces, is overflowing from the containing div.

For instance

If there are 7 dash placeholders at the end of the line, it breaks into 6 dashes staying on the top line and one dash moving to the bottom line.

This display looks messy. How can I prevent this issue and keep my guessing sentence as one continuous string?

var secretWord = 'A random text you need to guess without breaking in the middle of a word';

    secretWord = word.toUpperCase();

    var hiddenWord = '';
    var lettersAvailable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    for (i = 0; i < secretWord.length; i++)
    {
        if (secretWord.charAt(i) != ' ') hiddenWord += '-';
        else hiddenWord += ' ';
    }

    function showHiddenPart() {
        document.getElementById('WordBox').innerHTML = hiddenWord;
    }

    showHiddenPart();
    
window.onload = begin;

function begin(){
    var content_div = '';
    
    for(i = 0; i < 35; i++)
    {
        var element_code = 'l'+i;
        content_div += '<div class="letter" onclick="check('+i+')" id="'+element_code+'">'+lettersAvailable.charAt(i)+'</div>';
    }

    document.getElementById('alfabet').innerHTML = content_div;

    showHiddenPart();
}

String.prototype.UpdateChar = function(position, character) {
    if (position > this.length - 1) return this.toString();
    else return this.substr(0, position) + character + this.substr(position+1);
}

function check(number) {
    var selected = false;
    for(i = 0; i < secretWord.length; i++)
    {
        if (secretWord.charAt(i) == lettersAvailable.charAt(number)) {
            hiddenWord = hiddenWord.UpdateChar(i, lettersAvailable.charAt(number));
            selected = true;
        }    
    }
    if (selected == true){
        var identifier = 'l'+number;
        document.getElementById(identifier).style.background = "#003300";
        document.getElementById(identifier).style.color = "#00C000";
        document.getElementById(identifier).style.border = "3px solid #00C000";
        document.getElementById(identifier).style.cursor = "default";
        document.getElementById(identifier).style.boxShadow = "none";
        showHiddenPart();
    }
}
#container
{
    margin-left: auto;
    margin-right: auto;
    margin-top: 5em;
    display: grid;
    grid-template-columns: 1fr 1fr;
    width: 900px;
}

#WordBox
{
    grid-area: 1 / 1 / 1 / 3;
    text-align: center;
    font-size: 2.4em;
    min-height: 100px;
}

#alfabet
{
    grid-area: 2 / 2 / 3 / 3;
    min-height: 280px;
    display: grid;
    grid-template-columns: repeat(7, auto);
    grid-row-gap: .5em;
    grid-column-gap: .5em;
    justify-content: center;
    align-items: center;
}

.letter
{
    width: 30px;
    height: 30px;
    text-align: center;
    padding: 5px;
    border: 3px solid gray;
    cursor: pointer;
    border-radius: 12px;
}
<div id="container">
    <div id="WordBox"></div>
    <div id="alfabet"></div>

</div>

If any important part of the code has been missed out, please let me know. I appreciate any assistance as I have not been able to find a solution through online searches.

Answer №1

To ensure that the text does not break in the middle of any word, simply add white-space: nowrap; to #WordBox:

var word = 'Some text you have to guess and which should not break in the middle of any word';

word = word.toUpperCase();

var word1 = '';
var lettersToSwap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

for (i = 0; i < word.length; i++)
{
    if (word.charAt(i) != ' ') word1 += '-';
    else word1 += ' ';
}

function showHiddenWord() {
    document.getElementById('WordBox').innerHTML = word1;
}

showHiddenWord();
#container
{
  margin-left: auto;
  margin-right: auto;
  margin-top: 5em;
  display: grid;
  grid-template-columns: 1fr 1fr;
  width: 900px;
}

#WordBox
{
  grid-area: 1 / 1 / 1 / 3;
  text-align: center;
  font-size: 2.4em;
  min-height: 100px;
  white-space: nowrap;
}
<div id="container">
    <div id="WordBox"></div>
</div>

If you want to maintain line breaks and prevent dashed words from breaking, wrap them inside span elements and make them inline-block by updating your JavaScript as follows:

var word = 'Some text you have to guess and which should not break in the middle of any word';

word = word.toUpperCase();

var word1 = '';
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

for (i = 0; i < word.length; i++) {
  if (word.charAt(i) != ' ') word1 += '-';
  else word1 += ' ';
}

function showHiddenWord() {
  var r = '';
  for (var i = 0; i < word1.length; i++) {
    if (word1.charAt(i) != ' ') r += word1.charAt(i);
    else r += '</span><span>';
  }
  r = "<span>" + r + "</span>";
  document.getElementById('WordBox').innerHTML = r;
}

showHiddenWord();

window.onload = start;

function start() {
  var div_content = '';

  for (i = 0; i < 35; i++) {
    var element = 'l' + i;
    div_content += '<div class="letter" onclick="check(' + i + ')" id="' + element + '">' + letters.charAt(i) + '</div>';
  }

  document.getElementById('alfabet').innerHTML = div_content;

  showHiddenWord();
}

String.prototype.Swappo = function(place, sign) {
  if (place > this.length - 1) return this.toString();
  else return this.substr(0, place) + sign + this.substr(place + 1);
}

function check(nr) {
  var chosen = false;
  for (i = 0; i < word.length; i++) {
    if (word.charAt(i) == letters.charAt(nr)) {
      word1 = word1.Swappo(i, letters.charAt(nr));
      chosen = true;
    }
  }
  if (chosen == true) {
    var element = 'l' + nr;
    document.getElementById(element).style.background = "#003300";
    document.getElementById(element).style.color = "#00C000";
    document.getElementById(element).style.border = "3px solid #00C000";
    document.getElementById(element).style.cursor = "default";
    document.getElementById(element).style.boxShadow = "none";
    showHiddenWord();
  }
}
#container {
  margin-left: auto;
  margin-right: auto;
  margin-top: 5em;
  display: grid;
  grid-template-columns: 1fr 1fr;
}

#WordBox {
  grid-area: 1 / 1 / 1 / 3;
  text-align: center;
  font-size: 2.4em;
  min-height: 100px;
}

#WordBox span {
  margin: 0 5px;
  display: inline-block;
}

#alfabet {
  grid-area: 2 / 2 / 3 / 3;
  min-height: 280px;
  display: grid;
  grid-template-columns: repeat(7, auto);
  grid-row-gap: .5em;
  grid-column-gap: .5em;
  justify-content: center;
  align-items: center;
}

.letter {
  width: 30px;
  height: 30px;
  text-align: center;
  padding: 5px;
  border: 3px solid gray;
  cursor: pointer;
  border-radius: 12px;
}
<div id="container">
  <div id="WordBox"></div>
  <div id="alfabet"></div>
</div>

Answer №2

To implement CSS word-break property, follow the code below:

#TextContainer {
    word-break: keep-all;
} 

The keep-all value prevents breaks between certain characters. Here is the CSS Syntax:

word-break: normal|break-all|keep-all|initial|inherit;  

Refer to the documentation for more details: https://www.example.com/cssref/word-break

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance Laravel 5 by integrating browserify into the Elixir build process

My workflow for transforming coffee to js using browserify, browserify-shim, and coffeeify looks like this: I work with two main files: app.coffee and _app.coffee, designated for frontend and backend respectively. These files are located in resources/coff ...

Algorithm for File Naming

Given an array of desired file names in the order of their creation, where two files cannot have the same name. If a file has a duplicate name, it will be appended with (k), where k is the smallest positive integer that creates a unique name. Output an ar ...

What is the best way to position a button on the right side of the page, ensuring that all text

I need help aligning my button (JSX component) to the right side while ensuring that all text remains on a single line. I am working with next.js and tailwindcss, and the button includes plain text as well as a react-icon. These components are all wrapped ...

What steps can I take to condense and tidy up this output into a more compact string?

Recently, I've been experimenting with Google's APIs and attempting to create a terminal command that can inform me of the distance and travel time to a particular location. However, I'm running into an issue with the current output format: ...

Steps for displaying innerHTML values conditionally with a pipe

Currently working with Angular 8 and looking to conditionally implement the innerHTML feature using a translation pipe. .html <button type="button" mat-flat-button // utilizing translate module internally [innerHTML] = "display ? (HIDE ...

How come a colon within a function's body does not result in an error in JavaScript?

During my coding journey, I encountered a situation where I was attempting to return an object from an arrow function. However, I noticed that the code snippet below was simply returning undefined. After some investigation, I determined that the curly br ...

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...

Eliminating fillers dashes from a text

Imagine having a string filled with soft hyphens like the one below: T-h-i-s- -i-s- -a- -t-e-s-t-.- The goal is to eliminate these soft hyphens and get back the clean string: This is a test. Attempting this task in JavaScript, here's how far I&apo ...

Embellishing Your Website with Unique Cursor Styles

Looking to add personalized cursors to my website using asp.net 4.0. On my master page, I aim to set a custom cursor as the default for the entire site and have different custom cursors for all links. Is this achievable? ...

Should the article ID be sent to the ajax file, or should the ajax file retrieve the article ID directly? This dilemma arises in a

I am trying to pass the current article ID to an ajax file. The URL of the ajax file is something like www.web.com/plugins/system/ajax.php, so using JRequest::getInt(id) always returns 0 integer. However, in a non-ajax file, I can get the ID the same way. ...

Show the chosen value from the dropdown menu on all JSP pages

I have a header.jsp file containing a dropdown box labeled "Role". This header.jsp is designed to be included in all other JSP files using a directive. Once a user logs in, they are directed to a homepage where they must select a value from the dropdown ...

Can you explain the differences between offsetHeight, clientHeight, and scrollHeight for me?

Have you ever wondered about the distinction between offsetHeight, clientHeight, and scrollHeight? What about offsetWidth, clientWidth, and scrollWidth? Understanding these differences is crucial for working effectively on the client side. Without this kn ...

Leveraging JavaScript variables conditionally within a JSON object

Within the code snippet below, there is a condition written as (if (epsflag==0)<?php $a=",hide:'true'";?> ). I am looking to achieve the same condition using JavaScript. Essentially, I want to conditionally utilize a JavaScript variable in ...

Having trouble navigating the Request and Response handling in Expressjs/Nodejs?

As I continue to delve deeper into this code, confusion seems to cloud my understanding. Here is the provided source: var express = require('express') , http = require('http') , server = express() ; var home = require('./ro ...

What steps do I need to take in order to show the present value using a range input?

Hey there! I'm working on a code in HTML that includes an input of type range. Here's what it looks like: This is my input: <input type="range" min="1" max="100" value="50" class="slider" id="myRange"> Unfortunately, I'm unable to s ...

Is there a way to store div content in a PHP Session?

Just starting to learn php & ajax, so be patient with me. I have a clickable map. When the user clicks on a point, the value is displayed in a div. Once they select a point, they should be able to proceed to the next step. Now I want to save the content ...

Using Google Maps to trace a line showing the distance traveled

I want to create a 'distance traveled' polyline along a set route using V3 of the Google Maps API. The polyline should pass through multiple waypoints/legs. Currently, I am using the DirectionsService to draw the entire route. In addition, I a ...

The dropdown feature in Bootstrap 5 seems to be malfunctioning in Angular 12

I am facing issues while trying to implement the Bootstrap 5 dropdown in Angular 12. After installing all required packages and adding them to the angular.json file, I still cannot get it to work properly. Even after copying the example directly from the ...

The functionality of sending a response to a client in Node.js Express seems to be malfunctioning

I am facing an issue with sending a response back to the client. Despite not receiving any errors, it seems like the response is not working as expected. Can anyone help me figure out why? Below is my code snippet: exports.login = function (req, res, next ...

Why are you leaving a trail of timestamps in your .css files?

Within certain source codes, I have observed the following: <link rel="stylesheet" href="/css/style.css?201007071609" type="text/css" /> This prompts my question: What is the purpose behind appending 201007071609 to style.css in the code snippet ab ...