Cheat sheet: JavaScript - gouravtiwari/huddle-skeleton GitHub Wiki

What’s included in core.js

  • random image id by: getRandomImageId(startNum, endNum)

    Math.random() in javascript is used to return a random number between 0 and a number slightly less than 1, this will generate a random number between 10 and 20, which are the end and start values in this case. alert(Math.random()) on a document several times to see the results.

    The end result of the return maybe a decimal number, Math.floor() is used to round the value to the previous number. Eg Math.floor(14.98) will give 14

  • get image path: getImagePath(imageId)

    Return the string of the image path given imageId, for example, getImagePath(“10”) would return “images/10.jpg”

  • get keys of an object as array: allKeys(object)

    Return keys of an object as an array, for example,

    var obj = {};
    obj[1] = "a";
    obj[2] = "b";
    obj[3] = "c";
    // Calling allKeys(obj) would return [1,2,3]
        
  • find elements in the first array and not in the second array: diffArrays(firstArr, secondArr), for example
    var arr1 = [1, 2, 3, 4];
    var arr2 = [2, 4, 7, 8, 0];
    var diff = diffArrays(arr1, arr2); // value of diff is [1, 3]
        
  • get url parameter: getURLParameter(name), for example, your url is result.html?str={“10”:-2,”11”:0,”12”:-3,”13”:1,”15”:1,”16”:1,”17”:2,”19”:0}, calling getURLParameter(“str”) will return “{“10”:-2,”11”:0,”12”:-3,”13”:1,”15”:1,”16”:1,”17”:2,”19”:0}”

Array functions in JavaScript

Javascript arrays can be declared as var testArray = []; Some popular javascript inbuilt array functions

  1. Push – testArray.push(5); testArray.push(15); testArray now contains [5,15]
  2. Pop – Pop removes the last element from the array and returns it. 3) Length – testArray.length will give the value 2 in this case. This inbuilt function can be used to count the number of elements in the array or loop through the array. Also in javascript this is not a read only value, If you have 100 elements in an array and set the length to 50, Javascript will truncate the last 50 elements from the array (effectively deleting them).
  • concatenate string using ‘+’: “my” + “name” + “is:”
  • sort an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers : $.unique(arrayName)

Suppose an array contains the numbers 6,5,4,4,5,6,1 and you mat want to remove all the duplicate elements use the jquery function unique to remove the duplicate elements. This can be used as $.unique(arrayName). The above array would remove the duplicate 4’s, 5’s and 6’s.

  • reverse an array: reverse()
  • sort an array: sort()
  • click a link by class of the element: $(“.themeImage”).click()
  • attribute of element $(“.themeImage”).attr(‘src’)
  • A simple loop example

Simple loop function

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type ="text/javascript">
var count=1;
$(document).ready(function() {
$(".testdiv").click(function() {
  if(count==5) {
    alert("count is now 5, quitting!");
  }
  else {
    count++;
  }
});
});
</script> 
<body>
<div class = "testdiv">
<a href="javascript:void(0);" class="showNumber">Click me</a>
</div>
</body>
</html>

Example to sort object by values:

function sortByValues(score) {
    var sortable = [];
    for (var img in score) {
      sortable.push([img, score[img]]);
    }
    return sortable.sort(function(a, b) { return -1 * (a[1] - b[1]); });
  }

Things Good to Know

  • Transform an object to Json string:
var jsonStr = JSON.stringify(score);
  • Get url parameters with JavaScript:
function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

We have provided this function in core.js.

  • Redirect to another page:
window.location.replace("result.html?str=" + jsonStr);

jQuery

  • select class with $(“.className”)
  • select id with $(“#id”)
  • add function to handle click event, for example
$("#firstImage").click(function() {
    increaseRoundNum();
    checkRoundNum();
    trackScore(firstImageId, secondImageId);
    placeRandomImage();
  });
  • Replace html for specific tag with ID of X with Y, for example
$('#id')
  .html('<p>All new content.</p>');
  • Grab src attribute for specific tag with ID of X, for example
<img id="x" src="brush-seller.jpg" alt="brush seller" />
$('#x').attr('src');
  • Replace src attribute for specific tag with ID of X with Y
<img id="x" src="brush-seller.jpg" alt="brush seller" />
$('#x').attr('src', 'y');
⚠️ **GitHub.com Fallback** ⚠️