Separation of Concerns — Manipulating the DOM using JQuery

Ai Santos
HackerNoon.com
3 min readSep 21, 2016

--

I am working on a game project this week where users view scrambled words every time a page is refreshed or a button is clicked. Users can also view hints to guess the word. Users can then input their answer into a form and submit that form. If correct, users are given a score that is shown on the screen which adds or subtracts points based on their answer. Today we wrote 2 functions — RandomName and Shuffle. Inside of these functions we had mistakenly applied DOM events. Later I learned from a professional player that it is best practice to separate concerns and to write functions that handle bite size problems. The function shuffle receives a string input and has to turn that string into an array with each characflter split up into individual letters. Now an array, the letters have to then be shuffled and joined back together to form a new scrambled word.

First step: feed your function some data -

Next, write a function that will generate a random name from your data set.

What is going on here? Okay, let’s break it down. The function expression SHUFFLE takes in the data set random name. That data set is then split up into an array using the built in method .split. When you use this built in for javascript you need to make sure to feed it an empty string in order for the string to be split up into its individual letters. .split can also take in a parameter where you want to split the array. We then iterate through the array. We set a randomIndex variable that takes in the array’s length and multiplies that to get a random number based on the length of the array. We then assign the array’s value at that index in a variable called item. We then take that result at that index and then assign it to the a random index number and finally set that to item. We then join the new result array together to form the scrambled word. Whew.

Now it is time to manipulate the DOM! First we need to make sure our jQuery events fire when the DOM is ready. This is done with this line of code:

Next, select the html element that needs to show our shuffled random word. Inside this jQuery event handler, we also need to trigger the shuffle function on the word. All of this is beautifully handled by this line of code:

Finally, we need to fire this event again once the user clicks the scramble button:

--

--