MozillaZine


JavaScript question inserting variables into html elements

Discuss how to use and promote Web standards with the Mozilla Gecko engine.
Bethrezen
 
Posts: 431
Joined: September 13th, 2003, 11:56 am

Post Posted May 14th, 2022, 5:12 pm

Hi all

Quick question why is it that when I try to do something like this

Code: Select all
<p><script>document.write(color)</script></p>

<script>
var color = "blue";
</script>


I get a color is not defined error even though color clearly is defined ?

The reason I ask is because I got taught to put scripts at the end of the page to prevent them from blocking the loading of the page, but clearly in a case like this where I want to output the value of a variable to some element on the page that isn’t possible if I have to put the script that holds the variable before the html element in to which I’m inserting the value.

Now while in a simple example like this I could just do something like this

Code: Select all
<script>
  var color = "blue";
  document.querySelector('p').innerHTML = color;
</script>


What about if I wanted to do something a little more complicated like inserting a variable into a table for example.

ideally what I'd like to be able to do is something like this

Code: Select all
<script>

var x_coordinate = 100;
var y_coordinate = 200;
var z_coordinate = 150;

</script>

<table id="coordinates">
  <tr>
    <td>X</td>
    <td>:</td>
    <td>javascript:(x_coordinate); km</td>
  </tr>

  <tr>
    <td>Y</td>
    <td>:</td>
    <td>javascript:(y_coordinate); km</td>
  </tr>

  <tr>
    <td>Z</td>
    <td>:</td>
    <td>javascript:(z_coordinate); km</td>
  </tr>
</table>


as that's a simpler way to go about things or it would be if it actuality worked, now with a small table like the one above I could populate the cells like this

Code: Select all
var table = document.querySelector('table#coordinates');

table.rows[0].cells[2].innerHTML = x_coordinate;
table.rows[1].cells[2].innerHTML = y_coordinate;
table.rows[2].cells[2].innerHTML = z_coordinate;


But imagine you had a table with hundreds of cells that needed to be populated doing the above becomes completely impractical, so how then could I insert the variables into the appropriate table cells and have there values printed out when I load the page because doing

Code: Select all
javascript:(variable name);


simply doesn't work, is

Code: Select all
<script>document.write(variable name)</script>


the only way or is there a more succinct method.

mtalbot

User avatar
 
Posts: 39
Joined: October 13th, 2015, 5:21 am

Post Posted May 14th, 2022, 11:32 pm

A good place to start would be the MDN guides and the specific details for changing the color of a <p> element can be found on this page.

Bethrezen
 
Posts: 431
Joined: September 13th, 2003, 11:56 am

Post Posted May 18th, 2022, 1:44 pm

Two problems with that first off those pages won’t load for me I just get a blank screen, second even if I could get them to load they’re not helpful because they are not written for beginners to much technobabble that I don't understand and can't follow.

More over they usually don’t explain how accomplish the task I’m trying to accomplish, plus being dyslexic I find it much easer and faster to learn how to do a given task by simply asking questions certainly I have learned far more doing that then I ever did in the four and a half years I spent at collage studying wed development hence the question.

Certainly working on my own project as I have been has been an invaluable learning experience and while I have gotten better my knowledge is still pretty basic so I still need to ask a lot of questions when I run into things I don't understand particularly when I can't find an explanation that actually makes sense to me.

Anyway I digress so back to the question lets say I have a set-up like this

Code: Select all
<script>
var icons =
{
  icon1: {x: -609840, y: 1879080,z: -1617000},
};

for (var key in icons)
{
  var x_coordinate = icons[key]['x'];
  var y_coordinate = icons[key]['y'];
  var z_coordinate = icons[key]['z'];
}

</script>

<table id="coordinates">
  <tr>
    <td>X</td>
    <td>:</td>
    <td>x_coordinate; km</td>
  </tr>

  <tr>
    <td>Y</td>
    <td>:</td>
    <td>y_coordinate; km</td>
  </tr>

  <tr>
    <td>Z</td>
    <td>:</td>
    <td>z_coordinate; km</td>
  </tr>
</table>


The expected output would be

X : -609840 km
Y : 1879080 km
Z : -1617000 km

now of course the above doesn't work and what I actually get is

X : x_coordinate; km
Y : y_coordinate; km
Z : z_coordinate; km

because the browser isn't printing the value contained in the variable each time it loops of course this can be solved by doing

Code: Select all
<script>
var icons =
{
  icon1: {x: -609840, y: 1879080,z: -1617000},
};

for (var key in icons)
{
  var x_coordinate = icons[key]['x'];
  var y_coordinate = icons[key]['y'];
  var z_coordinate = icons[key]['z'];
}

</script>

<table id="coordinates">
  <tr>
    <td>X</td>
    <td>:</td>
    <td><script>document.write(x_coordinate);</script></td>
  </tr>

  <tr>
    <td>Y</td>
    <td>:</td>
    <td><script>document.write(y_coordinate);</script></td>
  </tr>

  <tr>
    <td>Z</td>
    <td>:</td>
    <td><script>document.write(z_coordinate);</script></td>
    </tr>
</table>


using document.write(); however probably isn't the cleanest or most elegant method so I'm wondering if there is a better way to do this, because I haven't been able to find anything, of course I'm aware that I could just do.

Code: Select all
var table = document.querySelector('table#coordinates');

table.rows[0].cells[2].innerHTML = x_coordinate;
table.rows[1].cells[2].innerHTML = y_coordinate;
table.rows[2].cells[2].innerHTML = z_coordinate;


instead of writing the variable in to the html as I did in the previous example but of course the issue with this method is that targeting rows and cells via there index value isn't exactly the easiest way to target elements and its very easy to get this wrong particularly if you have a very large table that has a lot of cells that need to be populated, and as I already mentioned above if you do have a table with lots of cells that need to be populated this method can become some what unwieldy and impractical, and its just easier to write the variable into the html and then have the browser print out value contained there in each time it loops.

jscher2000

User avatar
 
Posts: 11646
Joined: December 19th, 2004, 12:26 am
Location: Silicon Valley, CA USA

Post Posted June 27th, 2022, 11:07 am

Bethrezen wrote:Hi all

Quick question why is it that when I try to do something like this

Code: Select all
<p><script>document.write(color)</script></p>

<script>
var color = "blue";
</script>

I get a color is not defined error even though color clearly is defined ?

You already know this: Inline script tags are executed in order like other HTML tags. Thus, the error message is correct because color is not yet defined at the time it is referenced. If you prefer to use inline tags, you need to make sure all the relevant values are defined before you use them. While the advice is to defer all script code that isn't needed for the initial view of the page, for example, opening annoying overlays about chatting with an agent, that doesn't apply to scripts that are essential for the initial view of the page.

On the larger application, why do you want to fill in the table cells with client-side script? If the server can build the table before sending the page to the browser, that is most efficient. Sometimes the table needs to change based on user selections and in that case, you have the choice of either requesting a new page from the server (traditional) or requesting a set of rows or data from the server to update the page (more modern). The more modern approach isn't necessarily more efficient for the site. That could be why Google switched its search result pages back to traditional after many years of experimenting with "instant" results.

Bethrezen
 
Posts: 431
Joined: September 13th, 2003, 11:56 am

Post Posted July 14th, 2022, 10:05 am

When building I do everything locally on my desktop so server side code wont work of course I could get something like xampp which would let me run server side code locally but that’s a whole lot of messing around I’d rather avoid.

Besides the project I’m working on right now isn’t meant to be uploaded it’s only meant to run locally on my computer since its only really intended for my use I guess you could think of it as a project I devised as a sort of learning exercise although the end result once I’m done will have an actually use unlike so many of the simple demo pages that I’ve created to help me crystallise what I’ve learned or to help me learn something new

For example A simple demo page I put together to help me figure out the basics of responsive design, in the grand scheme of things it doesn’t really have any practical purpose but its good to have something to refer back to later.

Code: Select all
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>responsive design demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style>

*
{
box-sizing:border-box;
}

html,body
{
padding:0;
margin:0;
}

header
{
height:100px;
}

main
{
display:inline-flex;
}

div#left
{
width:66.66%;
padding:20px;
background-color:orange
}

div#right
{
width:33.33%;
padding:20px;
background-color:yellow
}

footer
{
background-color:pink
}

ul
{
margin:0;
padding:0;
list-style-type: none;
}

ul li ul li
{
padding-left:8px
}

img
{
display:block;
background-color:gray;
height:150px;
margin:0 auto
}

input,
label
{
display:none;
}

ul li ul
{
display:inline-flex
}

/* position the footer */

html, body
{
    height: 100%;
}

main
{
    display: flex;
    min-height: calc(100% - 40px);
}

@media screen and (max-width: 600px)
{
  ul,
  main
  {
    flex-direction: column
  }

  div#left
  {
    width:100%
  }

  div#right
  {
    width:100%
  }

  label
  {
    position:relative;
    display:inline-block;
    font-weight:bold;
    font-size:1.5rem;

    margin-left:30px;
    padding:2px 5px;
  }

  span
  {
    position:absolute;
    font-size:2.5rem;
    display:inline-block;
    left:-22px;
    top:-7px
  }

  ul li ul
  {
    display:none;
    margin-bottom:8px
  }

  input#menu:checked ~ ul li ul{display:inline-block}

}

</style>

</head>

<body>

<nav>

<input type="checkbox" name="button" id="menu">
<label for="menu"><span>&#8801;</span>Menu</label>

<ul>
  <li>
    <ul>
      <li>Link 1</li>
      <li>Link 2</li>
      <li>Link 3</li>
      <li>Link 4</li>
      <li>Link 5</li>
    </ul>
  </li>
</ul>

</nav>

<main>

<div id="left">

<img src="" alt="placeholder Image">

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>

<div id="right">

<img src="" alt="placeholder Image">

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>

</main>

<footer>Footer</footer>

</body>
</html>


I’ve built countless simple demo pages like that, I've one for building a lightbox galley, another for doing a slide show, I build another when I was trying to learn how to do drop down and pop out menus.

here is a screen shot of one of the pages https://i.ibb.co/brKTtXp/untitled.png of the project I'm working on at the moment the reason I was asking about populating tables was because I was trying to find out what the easiest way of getting the coordinate date to display in the table in the bottom left hand corner of the map screen was but as you can see from the screen shot I'm still having issues getting the numbers to display correctly hence my other question.

While people who are proficient with JavaScript could probably do something like this with ease for me its proving to be quite the challenge certainly its the most ambitious project I've attempted to date, and already I've learned a lot like the basics of event based programming, how to use data attributes.

b4ckerCrazyMit
 
Posts: 9
Joined: July 10th, 2022, 3:43 am
Location: Moz Office, SF, USA

Post Posted July 15th, 2022, 6:48 pm

Bethrezen wrote:


Can you describe it with doodle, it's hard to got the concept or what you want to achieve just by this statement. :shock: :?: :-k

Bethrezen
 
Posts: 431
Joined: September 13th, 2003, 11:56 am

Post Posted July 20th, 2022, 2:31 pm

Can you describe it with doodle, it's hard to got the concept or what you want to achieve just by this statement.


say what now I'm not following since your quote is empty ?

but essentially in this post viewtopic.php?f=25&t=3096498

I'm trying to figure out how to replicate the functionality of

Code: Select all
.toPrecision(3)


aka displaying a number to 3 significant digits the reason I'm trying to replicate the behaviour of .toPrecision instead of just using .toPrecision is twofold first .toPrecision rounds and so far as I'm aware there is no way to stop that since the .toPrecision method doesn't allow you to specify an optional parameter to control rounding which results in incorrect numbers being displayed for example 11.96054054054054 displays 12.0 when it should display 11.9

the second reason is because the project I'm working on is for a series of games specifically the X - Beyond the Frontier series therefore I'm trying to replicate the in game functionality as closely as possible and .toPrecision(3) is the JavaScript method that most closely replicates how coordinates display in game when you go to the map screen and highlight one of the objects in that sector

however currently as you can see in the this screen shot https://i.ibb.co/brKTtXp/untitled.png I'm having issues because the coordinates are not being displayed to 3 significant digits as it is in game.

Unfortunately the truncateDecimals function that was posted here: viewtopic.php?f=25&t=3096498

is not giving the right output because its displaying numbers to 2 decimal places not 3 significant digits so again 11.96054054054054 displays incorrectly and the output I get is 11.96 not 11.9 which is how that particular coordinate would display in game.

now the obvious solution here is to tweak the truncateDecimals function unfortunately my knowledge of JavaScript is insufficient so I don't know how because currently my knowledge of JavaScript is only about high school level so there is a lot I still don't know so I tend to get stuck a fair bit particularly when I'm trying to do something like this that I haven't done before.

Now as for this post I was trying to figure out the simplest way to get the coordinates from the script to display in the coordinates table.

I had though that I could just insert the x_coordinate, y_coordinate and z_coordinate variables into the table but when I loaded the page the contents of the variables where not being displayed because obviously I'd done something wrong unfortunately again I'm not sure what the proper syntax is for inserting variables into the html and having there contents displayed upon loading the page.

so I ended up using different way of getting the contents of the variables to display which while it works is trickier and doesn't really scale well if you need to populate a much larger table which led to jscher2000 question about doing things server side but of course since this is only really intended for my use and will be run locally from my desktop doing things server side isn't really an option and beside that is way over complicated for what should in theory at least be a simple task aka

display a set of numbers to 3 significant digits without rounding and if there are less then 3 digits then pad with zeros for for example 12 becomes 12.0 which is what .toPrecision does if there aren't enough digits to match the specified level of precision

unfortunately this supposedly simple task is actually proving to be devilishly tricky since JavaScripts inbuilt methods for doing this sort of a thing don't allow you to control how or if they round which is incredibly irritating and more that a little bit frustrating for a JavaScript beginner such as my self.

so hopefully that makes things clearer and you can see how the 2 posts are linked because they are about 2 different aspects of the same task.

Return to Web Development / Standards Evangelism


Who is online

Users browsing this forum: No registered users and 1 guest