Crafting an 'X' Shape with JavaScript

I am currently trying to write a program using JavaScript that will generate an 'X'. I am facing challenges in starting the code and deciding what commands to include in each line.

<!DOCTYPE html>
<html>
<meta charset="UTF-8"> 
<font face="Courier New">
<body>
<h1>Trying..</h1> 
<font face='Courier New'> 
<script> 
for (var row = 1; row < 5; row++) {
  for (var col = 0; col < max; col++) } {
    if (row===col || row + col===size-1) {
      document.write ('*')
    else
      document.write ('&Nbsp')
  }
</script> 
</font> 
</body> 
</html> 

This is my work-in-progress. I would greatly appreciate any assistance or guidance!

Answer №1

What a fun exercise! These two code snippets are identical.

var width = 10
var height = 10
var ratio = width/height; 

for (var row = 0; row < height; row++) {
    for (var col = 0; col < width; col++) {
        var diff = parseInt((row * ratio), 10);
        
        document.write (diff == col || col == width - diff - 1 ? '*' : '-')
            
        if(col == width - 1) {
            document.write ('<br>')
        }
    }
}

var width = 20
var height = 20
var ratio = width/height; 

for (var row = 0; row < height; row++) {
    for (var col = 0; col < width; col++) {
        var diff = parseInt((row * ratio), 10);
        
        if (diff == col || col == width - diff - 1)
            document.write ('*')
        else
            document.write ('-')
            
        if(col == width - 1)
            document.write ('<br>')
    }
}

Answer №2

Answer without the dashes... :)

Also, in document.write ('&Nbsp'), &Nbsp should be &nbsp to add space.

Non-breaking Space
A frequently used character entity in HTML is the non-breaking space: &nbsp;. A non-breaking space prevents a line break. Two words linked with a non-breaking space will stay together at the end of a line, avoiding disruption.

One important point to note

Note: Another common application of the non-breaking space is to prevent browsers from truncating spaces in HTML pages. If you type 10 spaces in your text, the browser may remove 9 of them. To retain actual spaces in your text, utilize the &nbsp; character entity.

var width = 10
var height = 10
var ratio = width/height;

for (var row = 0; row < height; row++) {
    for (var col = 0; col < width; col++) {
        var diff = Math.floor(row * ratio);
        
        document.write (diff == col || col == width - diff - 1 ? '*' :
 '&nbsp&nbsp&nbsp&nbsp') //Adjust the number of &nbsp to widen or narrow the X
            
        if(col == width - 1) {
            document.write ('<br>')
        }
    }
}

Reference : Non-breaking Space

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

Using jQuery to dynamically attach events to elements in a webpage

I am currently working with some ajax functionality. When a successful ajax request is made, additional content is dynamically added to the page. However, I am facing an issue where I cannot attach events to these dynamically added elements. The process i ...

Adding a trailing slash to the URL in an Express server causes it to be appended

I've encountered a strange issue with my express server. Whenever I try to use a specific URL route with the word 'bind,' an extra '/' is automatically added to it. This behavior isn't happening with other URLs that I've ...

ASP.NET MVC with AngularJS issue: post request does not trigger redirection

Why is the RedirectToAction not working and the URL does not change to /Home/Second when I make a post request to the Login? Using AngularJS: $scope.answer = function(answer) { $mdDialog.hide(answer); $http({ method: 'POST', url ...

What is the best way to push a variable after employing the split function in JavaScript?

error: An unexpected TypeError occurred while trying to read property 'push'. The error was on this line: " this.name[i].push(arrayData[0]); " I'm confused because the console.log statement before that line shows "data is loaded:" alo ...

Changing the visibility of a div with an onClick event in React

Can anyone help me figure out how to toggle the display of this div on click? I've been struggling with it for a while now. Any suggestions are welcome. https://i.sstatic.net/lPZtN.png https://i.sstatic.net/8Pybg.png ...

What is the best way to handle parsing JSON using external middleware after the removal of body parser in Express?

Having trouble parsing JSON with external middleware after Express removed the body parser? I used to rely on Express bodyParser for handling JSON posts, but after updating Express, my JSON requests are returning null. It seems like I was using the wrong ...

Triggering events on multiple elements with Vue.js when clicked

I am currently working on a feature that involves hiding and showing descriptions of image thumbnails when clicked by the user. I tried following a VueJS tutorial on transitions, but unfortunately only one thumbnail is properly functioning while the rest a ...

Is there a way to continuously cycle through multiple images fading in and out at various locations on a webpage using absolute positioning?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Harley's Art Gallery</title> <script t ...

Tips for capturing audio in flac codec format using JS/AJAX

Is there a way to record audio in flac codec instead of opus codec? I attempted setting the codec to flac like this: let blob = new Blob(audioChunks,{type: 'audio/ogg; codecs=flac' }); I also tried this: var options = { audioBitsPerSecond : ...

Formulate a Generic Type using an Enum

I'm currently working on a project that involves creating a generic Type using enums. Enum export enum OverviewSections { ALL = 'all', SCORE = 'score_breakdown', PERFORMANCE = 'performance_over_time', ENGAGEMENT ...

Enable the choice for Bootstrap collapse animation to be customized

Is there a way to allow users or admins on my website to decide whether or not Bootstrap 4 collapse elements should be animated? The concern is that when many elements are moved by the animation, it becomes less smooth. Therefore, it would be ideal to give ...

How to pass hidden values in an HTML form

There is a hidden HTML element within a form that looks like this: <input type="hidden" name="Something" id="Something" value="<?php echo "somevalue";?>"/> A JavaScript function changes the value of this hidden element. The question is: after ...

Receiving successful ajax responses and populating text fields with the returned values

I have been attempting to populate the values from an AJAX success response into their corresponding fields, but I am encountering some difficulties. Despite receiving the desired data in the "alert(responseObject)" within the success section, I am unable ...

Hmm, seems like there's an issue with the touchable child - it must either be native or forward setNativeProps to

Currently enrolled in a ReactNative course on Coursera, I am facing an error in a 4-year-old course: "Touchable child must either be native or forward setNativeProps to a native component." I am unsure about this error and would greatly appreciate any hel ...

Embed the parent component within the child component

I have two files called Recursive.vue and Value.vue. Initially, when Recursive is the parent component, mounting Recursive within itself works perfectly. Similarly, mounting Value within Recursive and then Value within itself also works fine. However, an ...

Exploring the possibility of designing custom pageload tooltips inspired by jQuery validationEngine's visual style and interface

My website incorporates the jQuery.validationEngine plugin to ensure the accuracy of user input. The tooltips that accompany this validation feature are particularly appealing; they gracefully fade in and vanish when users interact with them. To visualize ...

Error: JSON parsing error due to unexpected token C at the beginning of the string

When using ajax and json formatting, I am encountering this message. In PHP, the code array("message" => "Success", "data" => $data) is displayed successfully. However, it is not able to callback to ajax. How can I resolve this issue without deleting ...

guide to importing svg file with absolute path

I have been attempting to load SVG files from my LocalDrive using an absolute path. Despite successfully achieving this with a relative path, the same method does not work when utilizing an absolute path. <script> $(document).ready(functio ...

Is it beneficial to utilize components in order to streamline lengthy HTML code, regardless of whether the components do not repeat and do not require any props (such as in Vue or any other JavaScript library

In the Vue.js team project I am currently involved in, I have structured my code in the view as follows: component01 component02 ... There are more than 10 components in total. Each component represents a section of the landing page, consisting mostl ...

Having Difficulty Rendering Tube Shapes in Three.js

Having just started working with Three.js, I'm facing challenges in displaying a tube on the screen. Despite using a basic material to simplify lighting, the tube is not showing up as expected. Any assistance in troubleshooting this issue would be gre ...