About the Author:

Basics to Reading/Writing Cookies with JavaScript

January 17th, 2017

Cookies are relatively small text files that a web browser embeds on a user’s computer. Cookies allow otherwise stateless HTTP communications to emulate state (i.e., memory). Cookies are being replaced by somewhat newer technologies such as local storage and session storage; however, cookies are still widely used by many major websites today. For that reason alone, it’s a good idea for you to familiarize yourself with how cookies work. Additionally, it’s fun to see how you yourself can use JavaScript to read from and write to the your browser’s cookie API. In the following tutorial I’ll show you how to do precisely that. Let’s get cookie-ing!

First, let’s look at how to use JavaScript to read cookies: To achieve this, simply write document.cookie in your JS file or in your browser’s JS console. You can output the value to HTML or just simply log in the console. Here’s an example of what you might see if writing cookie data to HTML (Note: Your browser needs to have cookies enabled and values present for the demonstration to work):

See the Pen rjMjgp by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Yeesh.. what a mess! No worries, we can do some formatting. You’ll notice that there are = and ; interspersed throughout the cookie text. The = denotes key=value pairs while the ; delimits the individual pairs. So in order to clean things up a bit, you might write something like this:

See the Pen zNKZOj by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Much better!

Now, how to write cookies: To write cookies using JavaScript, simply use the same document.cookie property we looked at before, but this time set it equal to a key=value pair (as a string) using the assignment (=) operator. Like this:

See the Pen LxRWKV by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

See it? In green? I just added my email address as a cookie to your machine. Feel free to drop me a line! :) Of course you can delete it if you want…

Moving on, let’s say you want the value of just 1 key=value pair within the cookie. What to do..? Well, you could write a custom function to do something like this:

See the Pen zNKZdm by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

And from there, you can do all kinds of things depending on whether or not a certain key=value pair exists as a cookie on a user’s machine. One of the most common uses for cookies is keeping users logged in to a credentialed website (such as Facebook, Twitter, of YouTube) by placing a cookie on the user’s machine once successfully logged in. The logic goes something like:

    if (key=value exists) → show logged in content, if (key=value doesn’t exist) → prompt user to log in

that kind of thing.

And there you have it, a basic introduction to accessing and manipulating cookies using JavaScript. For more detailed information on cookies, you can always check out sites like MDN.

Thanks for reading!

About the Author:

EASY Speech Recognition and Speech Synthesis in JavaScript

December 19th, 2016

As a society, we’ve become increasingly intrigued by the concept of machines that can talk and listen. From fictional AI systems like HAL 9000 in 2001: A Space Odyssey (“I’m sorry, Dave. I’m afraid I can’t do that.”), to Apple’s Siri ,and Google’s new Assistant, our culture seems inexorably drawn to the idea of digital beings with ears and a voice. Implementing such sophisticated technology may seem far beyond the grasp of a beginner or even more experienced programmer; however, that assumption couldn’t be further from the the truth. Thanks to user friendly APIs found in modern browsers, creating simple speech recognition and speech synthesis programs using JavaScript is actually pretty straightforward. In the following tutorial, I’ll show you how to use JavaScript to access your browser’s speechRecognition and speechSynthesis APIs so that you too can create programs you control with your voice; ones that not only can hear you, but ones that can speak to you as well. Come, let’s have a listen…

Explore JavaScript Courses

To start, it’s typically a good idea to explore which browsers best support the technologies we’re going to be working with. Here’s MDN’s spec sheet for the speechRecognition API: https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition#Browser_compatibility. As you can see, it’s pretty much Chrome leading the way; however, Firefox has some capability as well. The same holds true for the speechSynthesis API: https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis#Browser_compatibility. Do note that Microsoft’s Edge browser enjoys some speech synthesis capabilities. David Walsh wrote a nice article on setting up the speechSynthesis API for cross-browser functionality; but, for simplicity’s sake and for the remainder of this tutorial, I’m going to assume the use of Chrome. 

So what does the code look like? A simple example of speech recognition code (written in JavaScript) looks like this (NOTE: You’ll probably have to open a new tab/window by clicking the “Edit in JSFiddle” link AND allowing your the browser access to your computer’s microphone (it should prompt you to do so).):

Try it out. Give the browser access to your computers mic and then try saying a few different words or phrases. If all goes according to plan, you should see what you say being written to the body of the html. If you’re having trouble getting it to work, try:

1) Making sure your computer has a mic and that your browser has access to it.

2) Making sure you have open only 1 application/tab/window that’s using the microphone.

3) Making sure to use Chrome as your browser and loading up the JSFiddle example in a new tab/window.

Okay, so the above example simply writes what the computer heard to the body of the html. That’s pretty interesting, but now let’s do something a bit more fancy; let’s tell the computer to do something for us! In the following example, trying opening up the Fiddle and telling the browser to change the background color of the HTML. The way I programmed it, you’ll have to say this exact phrase:

“Change background color to…” and then say any of the many colors recognized by CSS (e.g., “red,” “blue,” “green,” “yellow,”etc.).

Pretty cool, right? And really not all that difficult to pull off!

Now let’s look at giving the program a voice. I’m going to use Chrome’s default voice (yes, it sounds pretty robotic); but once you get the hang of it, feel free to read up on how to get and use different voices. Here we go; let’s see what it’s got to say:

Hear that? This time, the program audibly confirms that it’s changing the color of the background! Fantastic.

To recap all of this…

Speech Recognition

– The browser’s speechRecognition object has start and stop methods you can use to start and stop listening for audio input.

– The speechRecoginition object can react to for onend and onresult events.

– To get a string/text of what the computer heard, you can pass the onresult event to a function and then reference the event.results[0][0].transcript property.

Speech Synthesis

– The speechSynthesis object has a speak method that you can use to utter new SpeechSynthesisUtterances.

– You can pass a string (or number) value to the SpeechSynthesisUtterance constructor to create words or phrases.

    – pass that whole thing to the speak method and you’ve got a talking computer!

And there you have it. In this tutorial I’ve shown that it’s relatively simple to employ speech recognition and speech synthesis technology in your browser through the use of JavaScript. With this new tool set, my hope is that you’ll explore the wide array of possibilities that now exist. In theory, you can program your browser to execute most if not all of its functions at the sound of your voice. And you can make the browser say pretty much anything you want it to say. As usual, the limit is your imagination; so get out there and say something interesting! Better yet, have your browser say it for you. ;)

Explore JavaScript Courses

About the Author:

Finding the Most Frequent String in a JavaScript Array

October 21st, 2016

In the following tutorial, I’ll show you how to write a function that takes an array of strings and returns the most frequent string(s) in that array. First I’ll go through the basic concepts and setup, we’ll test it to make sure it works, then I’ll explore a few ways in which you can handle bad data and errors. We’ll also consider some ways to make the outputted data more user friendly. Let’s get started!

We’ll start with a pure function, one that takes an array of strings as input and returns another array as output (the outputted array will ultimately contain the string(s) that occur most frequently in the input). The setup looks like this:

   function mostFreqStr (str) {
      var which = [];
      return which;
    }

Next we’ll define an object that we’ll fill with data, using the strings in the array as keys and the number of times those strings occur as values. We’ll also add in a mostFreq variable that will be used to keep track of how many times the most frequent string(s) occur(s). The code now looks like this:

   function (arr) {
      var obj = {}, mostFreq = 0, which = [];
      return which;
    }

Now we’ll get in to the meat of the function, the processing logic. I’ve chosen to use JavaScript’s native forEach method that is an inherent to all arrays. If for some reason you wanted to use a for or while loop, you could do that as well. Here’s what the forEach approach looks like using ECMAScript 6 syntax (don’t worry, we’ll discuss the logic involved right after looking at the code):

    arr.forEach(ea => {
      if (!obj[ea]) {
        obj[ea] = 1;
      } else {
        obj[ea]++;
      }

      if (obj[ea] > mostFreq) {
        mostFreq = obj[ea];
        which = [ea];
      } else if (obj[ea] === mostFreq) {
        which.push(ea);
      }
    });

The logic is this: the ea variable represents the current array element on each iteration of forEach. The first if statement asks Does the string represented by ea exist as a key in obj? If the string is not the name of a key in obj (i.e., if obj[ea] === undefined evaluates to true), then we declare and initialize in obj the string represented by ea. We initialize it to a value of 1. The value 1 here represents the number of times we’ve encountered the string in arr. On the other hand, If the string is already the name of a key in obj, then we increment that key’s value by 1 (i.e., we add one more to the count of how many times we’ve seen the string in question in arr).

The second if block there is used to compare values of the keys in obj (i.e., the strings in arr) to the current most frequent count (i.e., the value of mostFreq). mostFreq was initialized equal to 0, so if the value of ea in obj is greater than 0 (as it will be as for any string encountered in arr), then mostFreq is updated to the value of obj[ea]. Additionally, the which array gets added to it the current value of ea (i.e., the current string in our iteration through arr). The else if portion of the second if block accounts for the condition where two or more strings in arr share the current value of mostFreq. If two or more strings in arr share the condition of being most frequent in arr, then the latter string(s) encountered is/are pushed to the which array so that they can equitably share the title.

The final step in our function is to return the newly populated which array. The entirety of the code looks like this:

    function mostFreqStr (arr) {
      var obj = {}, mostFreq = 0, which = [];

      arr.forEach(ea => {
        if (!obj[ea]) {
          obj[ea] = 1;
        } else {
          obj[ea]++;
        }

        if (obj[ea] > mostFreq) {
          mostFreq = obj[ea];
          which = [ea];
        } else if (obj[ea] === mostFreq) {
          which.push(ea);
        }
      });

      return which;
    }

Here it is live with a few tests so that we know it’s working:

See the Pen NRLWdz by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

But let’s say we want to make it a little more user friendly with respect to the output. We can convert the which array to a string by using Array’s toString method. We can then append a sentence (using ES6 template literals) in order to clarify the output. Like this:

    which = `"${which.toString()}" is the most frequent string in the array.`

Examples of input and output:

    console.log(mostFreqStr(["x", "x", "y", "y", "y", "z"]));
    //"y" is the most frequent string in the array.
    
    console.log(mostFreqStr(["x", "x", "x", "y", "y", "y", "z"]));
    //"x,y" is the most frequent string in the array.

Hmm… that second one doesn’t look quite right. We can write in some logic to handle our output sentence’s grammar when there’s more than one most frequent string. I’m going to use Array’s join method in order to help us out here. Here’s the live version:

See the Pen kkRaBd by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

There we go!

Now… for one final consideration… error handling. What if someone passes in some bad data? Or let’s say someone tries to pass in two arrays instead of just one; or perhaps an array that contains an element that isn’t a string. What someone tries to pass in data that isn’t an array at all? Let’s write some logic to handle these erroneous conditions. Live example:

See the Pen YGOzRA by Chase Allen (@ccallen001) on CodePen.

And there we have it! A function that takes an array of strings as input, checks for and handles potential errors, and ultimately returns a user friendly response indicating the most common string(s) in the array. Please feel free to comment and share. Thank you for reading!

About the Author:

How to Make Circular/Curved Text with JavaScript

September 28th, 2016

Creating circular text, or text on an curved path, in webpages may seem like somewhat of a intimidating task. There isn’t really a straightforward way to achieve it with standard HTML and CSS. There is a JavaScript plugin or two out there with some pretty decent results, but using plugins means extra dependency and load time associated tacked on to your project. So… what can you do? With a little bit of plain old vanilla JavaScript and standard CSS, it’s actually not that difficult to create curved text of your own! In this article, I’ll show you how to create circular/curved text that relies on as little as 15 lines of JavaScript. The result is functional and reusable so that you can apply as much circular text to your projects as you would like! You won’t need any special libraries or plugins of any sort; just good old fashioned HTML, CSS, and JavaScript. I’ll provide examples as we go, and I’ll provide items for consideration along the way. Circle the wagons; let’s get started!


Circular Text: The HTML

We’ll start by setting up the HTML, which is pretty much as simple as it gets. You’ll want a container for the circular text (although not 100% necessary) as well as a target element in which you’ll insert your circular text. Here’s how I’ve got it set up:

See the Pen ALoKJJ by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The CSS

Next we’ll add a some CSS to get things set up. None of the following CSS is actually necessary, and it can be adjusted as needed. For the purposes of this tutorial, I chose a purely arbitrary blackish background with whitish text; I also chose to center the target element (the div with class=circTxt), but you can choose to position the containers and target elements however you please! Here’s how I have the CSS:

See the Pen NRvNEv by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The JavaScript

Next comes the magic, the JavaScript. Things get a bit more complex here, but the overall logic isn’t really all that difficult. To give a broad overview before actually looking at the code, here’s what we’ll want to accomplish:

  1. Create a reusable function named circularText that takes 3 arguments: 1) the text to be written in circular fashion, 2) the radius of the circle on which the text will lie, and 3) the DOM index of the target class=circTxt element
  2. Split the text in to an array and get it’s length (i.e., the number of characters it contains)
  3. Divide the total degrees in a circle (i.e., 360 deg) by the length/number of characters in the text to determine spacing
  4. Specify the origin, or starting point, for the circular text (for simplicity’s sake, I’m going to hardcode 0 degrees)
  5. Create a loop (here using Array’s forEach method) that inserts the text around the perimeter of a circle using the defined radius and updating the origin/start value as it goes
  6. Call the function to create the circular/arced text!

Got all that? Believe me, it’s really not that complicated; less than 15 lines if you please. Here’s what the code looks like:

See the Pen rrzZoK by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

NOTE: I am do use ES6 syntax there (the arrow function and the template literal), but the code can easily be refactored to comply with more traditional syntax.


Well… there you have it… circular text with plain old HTML, CSS, and JavaScript!

Some things to consider are the need for adjusting the passed radius value based on how many characters are in your text. Generally speaking, the more characters you have in your text, the larger the radius you’ll need to use (however, you can create some neat effects by using a radius that might initially appear to be too small). Also note that you can created arced or curved text without going around a full circle by being purposeful about using spaces in your text.

See the Pen kkobjp by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

The arc effect can also be achieved by modifying the origin value used in the code (i,e., starting somewhere other than at the top of the circle). Regarding modifications to the CSS, the code could be changed to target elements with specified ids or tag names; you could use the document object’s querySelector method to achieve precision targeting as well. Additionally, you can modify both the circTxt containers (positioning them wherever you like on the page, giving them height and width, etc.) and the circular text within.

See the Pen Circular Text Generator by Chase Allen (@ccallen001) on CodePen.

I encourage you to go wild, get creative with it, circle back and have some fun! :)