Setting up a Javascript experiment.


Setting up a JavaScript Experiment

Whenever I do an experiment for JavaScript, I set up an html file, and a javascript file.
*The css file is just because I want it to be pretty, totally optional, but don't go overboard it isn't necessary for the experiment*

Pictured below is the current project I'm working on, and I need to figure out how the 'Search' input works in google fonts.  I'm not going to be able to duplicate what google does to make this happen, so I need to find a way to do it myself.  I'm clueless as I write this, but that is where the experiment comes in.



With Python, I'd run all the experiments in the command prompt / powershell / terminal.  Python does what it's gonna do in the system, that is where the process is run.  *Let's ignore Django exists yeah?

Javascript on the other hand will have different reactions in a Browser, because the browser carries out it's own rules and interpretation of the code then the terminal would.  So to get a real feel of what you want your javascript to do, we want it interacting with the browser just like it would in an online application process. 

You don't even have to be online for this to work.  If you have your 'chrome' or 'firefox' or what have you installed in your PC, it can run the files locally without even having internet.  Just click the html file, and I believe most computers will fire up the corresponding browser to run it.

This is only the first steps in setting up the Experiment.  I will be writing another blog post to go more into depth on the javascript and testing of the search algorithm.


First steps:  Write the files for the code to run in. 

If there's a IDE involved like VS code, it will give you a template when you open a new file of the specified type, if you don't, feel free to copy a basic html like the one below, and go from there.  Remember experiments are meant to be modified, tampered with and destroyed if necessary to learn what you need to.   A lot of mistakes lead to new discoveries.  If something is broken, it's a great way to learn why.

Is your page completely empty?  You might be missing the closing script tag.
To link a javascript file in the head, you do this:
  <script type="text/javascript" src="filename.js"></script>
Since the file <yourfilesname.js> is in the same location/folder, the browser will find it. This works locally, since the browser, chrome or whathaveyou is installed in your system. When it runs the html, it establishes the path to that file, and can locate all the others in the same file. 
Now another important bit,  making the functions go.  I've done it, I still do it.... don't forget to call those bad boys or they won't do anything HaveFun().
I'm gonna share a little other piece I use all the time.  This bit of code will, when the window has and event, which is load, run whatever you've told it to.  Pop this at the bottom of your Javascript file, and whenever you make a code change, you can refresh your browser and see what the new code does. 


window.addEventListener('load', (event) => {
    HelloWorld()
    Goodbye()
});


ERRORS: 

There is an error in the <head> that took me a minute to find and fix.  This is why it's important to run a few tests first.  Otherwise, a person might think the error is in their javascript, when really it was an html tag that was not closed properly.

While the css is optional, I highly recommend it.  It helps to visualize what's going on if the elements are neatly laid out for display.  Whenever I set up a css, I go through the html, and in the order they appear in the html, write a css block for them.  CSS is a whole different beast, so feel free to just copy and paste it,  or if you are familiar with bootstrap and it's use, go ahead with that.

The basic files:

HTML

--start code block HTML --

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8" />
    <!--  viewport for mobile users -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- links to our css(optional) and javascript file-->
    <link rel="stylesheet" href="custom_js_experiment101.css" />
    <!--  THE ERROR script looked like this:

        <script type="text/javascript" src="js_experiment101.js" />

        Because the closing tag was missing, when I ran the HTML, the body was empty.
        If something has completely dissappeared from your page, HTML is probably ignoring it for some reason.
        -->
    <script type="text/javascript" src="js_experiment101.js" /></script>
    <!-- title for the page-->
    <title>javascript search</title>

</head>

<body>
    <h1> Search in an array for a close or matching string set:</h1>
    <!--  ADDED FOR TEST -->
    <h3 id="test"></h3>
    <h4> The array: ['ant', 'attic', 'anticipate', 'bore', 'boredom', 'cat', 'borealus', 'dog', 'emu', 'frog', 'snippet', 'match', 'matrix', 'mutton']</h4>
    <main>
        <!--  a search input for user interaction -->
        <form>
            <!--    ADDED  -->
            <input placeholder="Search here" id="search" />
            <!-- A reset button to reset search parameters-->
            <input type="reset" value="reset" />

        </form>

        <div class="deck" id="deck">
            <div class="results_card" id="results_card" style="border: solid 2px red;">

                <!-- ADDED -->
                <h3> The array word </h3>

            </div>
        </div>
    </main>
    
</body>
</html>

--end code block HTML--

If you didn't see the Error message in the above HTML code, I didn't properly close the <script> tag in the <head>.  This resulted in about 30 minutes of me figuring out why my <body> was empty in the web dev tools of chrome.

This is why making sure everything is working properly before tackling the algorithms is important.  If I had written a bunch of code first, I might not have realized the error was in my html code and not in the javascript I wrote.  Because... well, of course it must be something I did in the javascript.

Nope.

HTML has a habit of ignoring anything it can't read, and just outputting what it can.  In this case, it saw an open script tag, and decided everything else was unimportant and spit out an empty body to make up for it.

CSS

--start code block css (OPTIONAL) --

* {
    margin: 0;
    padding: 0;
}
body {
    margin: 0;
    padding: 10px;
    background: black;
    color: #EFF1EA;
}
 h1,h2,h3,h4 {
     text-align: center;
     margin: 10px;
 }

#test {
    text-shadow: 2px 2px #a614f1;
}


main {
    margin-top: 10vh;
    background: #EFF1EA;
    color: #501A10;
    font-family: monospace;
    border-radius: 15%;
}


form {
    display: flex;
    flex-direction: row;
    margin: 10px;
    align-content: center;
    justify-content: space-evenly;
}
input{
    font-size: 1em;
    height: 2em;
    border: solid 1px white;
    background: black;
    color: white;
    padding: 10px;
    border-radius: 0.5em;
}
.deck {
    display: flex;
    flex-direction: row;
    align-content: center;
    justify-content: space-evenly;
}
.results_card {
    display: flex;
    flex-direction: column;
    width: 20vw;
    height: 20vh;
    border: solid 1px white;
    background: #D9DAD6;
    color: #140742;
}

--end code block css ----

The Javascript file is empty at this point.  I need to know what elements in the HTML I'm going to manipulate and change.  What items I am going to need javascript to change, alter or retrieve.

So far I need:
      the input value -- id="search"
      the array, which I will predefine for this experiment:
            [
                'ant', 'attic', 'anticipate', 'bore', 'boredom', 
                'cat', 'borealus', 'dog', 'emu', 'frog', 'snippet', 'match', 'matrix', 'mutton'
            ]  *see notes below*
And the place I'm going to arrange the results:
          the card deck -- <div> id="deck"
and it's future child nodes:
          the cards --<div> id="results_card"
Finally a test element to run a function on after window load to make sure all files are cooperating properly.  -- id="test"
         

This is where a little css can help if you need visual confirmation.  If you don't want to do a css file, just add some distinct borders *and margins*  to your results_cards.   This way you know when they are failing to appear, and where they are on the page more easily.  I'd suggest something like:

--code block example--
 <div class="deck" id="deck">
            <div class="results_card" id="results_card" style="border: solid 2px red;"></div>
        </div>

--code block end --


Note about the array:
When I built python sorters, I found there were some errors in the process when dealing with double letters, like attic,  and errors that came with words that started with the same letters, but then one had more or less.  like ant and anticipate.   So to make sure I'm getting proper results, I included these kinds of words into the array.   If it doesn't sort them properly or fails to identify the matches how it should, I can look first at errors I had previously with these similarities in the strings.  It may not matter in the end, for all I know javascript has a way to sort these without me even having to attempt my own algorithm, but this is why we experiment.

Next step:  Add some Javascript
Lets get something in the Javascript file.  We need to first make sure all the files will run together properly.  (Get the elements' id(s) matched, DOM elements, and file names confirmed).  Did everything appear as it should, where it should?  Before working on the algorithms, or more complex pieces, if this bit is broken, the rest will be impractical to work on.


JAVASCRIPT
-- start Javascript code block--

// JavaScript source code
// Experiment 101, design a users search 

let deck;
let results_card;
let search; //<---  added id="search" to the html search <input>
/* added for the test */
let test;


/* We can make the array constant, because we do not want the original to change.
 * We'll make a duplicate to sort and rearrange for the pages search results.
 * Then if there's some catastrophic error, or original array is untouched by the sorting
 */
const search_array = ['ant', 'attic', 'anticipate', 'bore', 'boredom', 'cat', 'borealus', 'dog', 'emu', 'frog', 'snippet', 'match', 'matrix', 'mutton'];



/*  create a function to set the dom elements after the page has loaded.
 *  If the javascript tries to read an element before the page has finished loading,
 *  it will return that it is undefined.  Then making it unmodifiable to us.
 */

function set_DOM() {
    /* The elements at the top are the ones I know I'm going to manipulate so far.  
     * I can add elements as I go to the top, and in this function. 
     * I can name the elements what they are named(id=) in the HTML,  these variables will not
     * conflict with each other in the javascript and it makes it easier to track all the items.   
     */
    deck = document.getElementById("deck");
    results_card = document.getElementById("results_card")
    search = document.getElementById("search")
    test = document.getElementById("test")
}

/* Lets make sure everything is working by adding a function that will change something in the 
 * HTML after the load is complete,  we can just take this bit out when we're done.
 */
function test_function() {
/*Change the inner HTML of an element I've added for the test*/
    /*this element is set up in the set_DOM(), we can now manipulate it freely within functions*/
    test.innerHTML = "THIS TEST ELEMENT IS LOADED AND READY."

}

/* The html will read the javascript file, because it is linked in the <head> first, before the html is fully loaded.
 * For this reason, we will tell it to set the DOM elements in this javascript file, after the page is done.
 * Otherwise we'll get elements that are undefined, because well, the page hasn't loaded them yet.
 */

window.onload = function load() {
    /* We'll set up all the things we want done after the window is loaded,
     * and that we want the javascript file to be able to access and use after load here.
     */
    set_DOM()
/* event listeners will also need to be active after the page is fully loaded */
/* elements are loaded, we can run our test.*/
    test_function()
}



--END javascript code block--






Image:  End results of the code running together.  The test phrase appears on the page, highlighted with text-shadows, meaning everything set up, and ran. 



Conclusion:

So this is a set up I made for my experiment I'll be working on in a future post.  The css is important to me, because I need to easily see what the page is doing.  While the algorithms take a lot of work to get running properly, if the page can't display the end results of whatever your trying to create, it's hard to know what is failing, and what is succeeding. 

Experiments can help us learn what's going on, and where.  When to blame the HTML, or when to look deeper into our JavaScript,  this is where console.log() will come in for the next part of the experiment.  If something is hard to figure out or understand, my first step is to design a page to play with the concept that is proving difficult.  Whether it be python, or web dev, taking smaller pieces and understanding them can make seeing the bigger picture easier. 

And if you break an experiment, it's not going to hurt anything, and you may learn more in the process if your not worried about messing up origin code.  Like in the picture at the start of the blog, I have a ton of hours into what I already have.  I'm not going to go about making the search algorithms directly in the files already working *mostly* properly.  I experiment like this, and come up with viable code, test it, and make sure it's going to work first.  Python I would make a small snippet of a class and play with it.  With the linked lists, the nodes were such a new concept to me, I played and manipulated them a lot before even starting to write the actual linked list.  Knowing which way the gears are turning to drive the machine is helpful. 

As always,  take it, break it, have fun. 
Feel free to drop a comment or ask me any questions. I'm always open to ways to improve a post, or make it more useful. 

May the spam be ever in your flavour.








Comments

Popular posts from this blog

playing with color in powershell python

JavaScript Ascii animation with while loops and console.log

playing with trigonometry sin in pygame