Week5 Video 3 Function Naming - A Familiar Example: $()

by Lucille Kenney

HTML

<b>Function Naming</b>

<div>
    <ul>
        <li id="firstListItem">Function names can begin with $, _ or a letter (but not a digit)
            <li>Function names can contain letters or numbers or some punctuation
                <li>Javascript operators are not allowed
                    <li>While unicode characters are technically allowed, it's safest to stick to standard ASCII, and avoid punctuation marks other than _ or $</ul>So, let's do an example: <code>$()</code> That's a totally legal function name. And let's have it get the element with id <code>id</code> and if it exists, return it.
    <p>Output will appear below:</p>
</div>
<div id="output"></div>

CSS

#output {
    width:80%;
    border: 1px solid black;
    padding: 1em;
}

JavaScript

// The function name '$' is used 
//   by several prominent JS libraries,
//   including JQuery
//  e.g.  $(myElement)

//  Here's a simple-as-possible implementation 
//  of this function: get the element by id and return it
function $(id) {
    if (id && document.getElementById(id)) {
        return document.getElementById(id);
    }
}

// let's see the output
logMessage($("firstListItem").innerHTML);



// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id) {
    if (!id) {
        id = "output";
    }
    document.getElementById(id).innerHTML += msg + "<br>";
}