Skip to content

Instantly share code, notes, and snippets.

@tachymetre
Last active September 7, 2016 02:35
Show Gist options
  • Save tachymetre/5b9341c6d0d903d17db6 to your computer and use it in GitHub Desktop.
Save tachymetre/5b9341c6d0d903d17db6 to your computer and use it in GitHub Desktop.
UI-101 (Scenario)
  1. Create an unordered list with no class and no id. When clicked, send an alert window to show which list has been clicked. Use Javascript or jQuery - Answer: ```html
  • Coffee
  • Milk
  • Soda
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> /* The jQuery way */ $(document).ready(function() { $("li").each(function() { $(this).on("click", function() { alert($(this).text()) }); }); });
/* The JavaScript way*/
var x = document.getElementsByTagName('li');
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener('click', function() {
        alert(this.innerText);
    });
}

/* Event Bubbling in JavaScript */
document.getElementsByTagName(“ul”)[0].addEventListener(“click”, function(e) {
    if (e.target && e.target.tagName.toLowerCase() == “li”) {
        alert(e.target.innerText);
    }
});

/* Event Bubbling in jQuery */
$(function() {
    $("ul").on("click", function(event) {
        alert($(event.target).text());
    });
});

/* Special Use of .on(), see API documentation*/
$(function() {
    $("ul").on("click", "li", function(e) {
        alert($(this).text());
    });
});
</script>
```
  1. Create an image of 500px by 500px and place it to the center of browser window using CSS - Answer: ```html

Pulpit rock

<style> /* The first way */ img { position: absolute; top: 50%; left: 50%; margin: -50px -50px; }
/* The second way */
img {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}
</style>
```
  1. Create a start system rating with these following requirements: 1. The total number of stars is 6 2. Initiate with white star 3. When click on one of these stars, this star and those on left of this star change to solid star Image of stars rating
- Answer:
```html
<!-- HTML -->
<div class="rating">
    <input type="radio" name="rating" value="0" checked /><span id="hide"></span>
    <input type="radio" name="rating" value="1" /><span></span>
    <input type="radio" name="rating" value="2" /><span></span>
    <input type="radio" name="rating" value="3" /><span></span>
    <input type="radio" name="rating" value="4" /><span></span>
    <input type="radio" name="rating" value="5" /><span></span>
</div>
```

```css
/* CSS */
#hide {
    display:none;
}
.rating input {
    position:absolute;
    filter:alpha(opacity=0);
    -moz-opacity:0;
    -khtml-opacity:0;
    opacity:0;
    cursor:pointer;
    width:17px;
}
.rating span {
    width:24px;
    height:16px;
    line-height:16px;
    padding:1px 22px 1px 0; /* 1px FireFox fix */
    background:url(stars.png) no-repeat -22px 0;
}
/* Change span immediately following the checked radio */
.rating input:checked + span {
    background-position:-22px 0;
}
/* Reset all remaining stars back to default background.
   This supersedes the above due to its ordering. */
.rating input:checked + span ~ span {
    background-position:0 0;    
```

Another Way
```html
<!-- HTML -->
<div class=”rating”>
    <a href=”#a1” id=”a1”>&#9734;</a>
    <a href=”#a2” id=”a2”>&#9734;</a>
    <a href=”#a3” id=”a3”>&#9734;</a>
    <a href=”#a4” id=”a4”>&#9734;</a>
</div>
```

```css
/* CSS */
.rating {
    unicode-bidi: bidi-override;
    direction: rtl;
    text-align: center;
}
.rating a {
    display: inline-block;
    position: relative;
    width: 1.1em;
}
.rating a:target, .rating a:target ~ a {
    color: transparent;
}
.rating a:target ~ a:before {
    content: “\2605”;
    position: absolute;
    left: 0px;
    color: gold;
}    
```
  1. When the code below is executed, what value is logged to the console? Please explain

    var a = 7;
    
    function foo() {
        this.a = 13;
        bar();
    }
    
    function bar() {
        console.log(this.a);
    }
    foo();
  2. Refactor and optimize the following:

    var arr = new Array();
    arr[0] = "apple";
    arr[1] = "orange";
    arr[2] = "banana";
    for (i = 0; i < arr.length; i++) {
        var rx = new RegExp("^a*b+", "g");
        console.log(arr[i].match(rx));
    }
  3. Explain why the value of foo.count is never incremented

    function foo(num) {
        console.log("foo: " + num);
        this.count++;
    }
    foo.count = 0;
    var i;
    for (i = 0; i < 10; i++) {
        if (i > 5) {
            foo(i);
        }
    }
    // foo: 6
    // foo: 7
    // foo: 8
    // foo: 9
    console.log(foo.count); // Still 0!
  4. Rewrite the above example so that foo.count is properly incremented

  5. Rewrite the test condition in the if statement so that the expression inside the conditional block is executed

    var a = 0.1,
        b = 0.2,
        c = a + b;
    if (c === 0.3) {
        console.log("Math is fun!");
    }
  6. Explain how the value of var a can be truthy, and yet not loosely equal to true

    var a = 13;
    var b = true;
    if (a) {
        console.log(Boolean(a)); //true 
    }
    console.log(a == b); // false
  7. The following utility function extends an object by adding properties and methods from an extension object. Unfortunately, extend has a bug. Can you spot it?

    var extend = function(obj, extension) {
        if (typeof obj === "object" && typeof extension === "object") {
            for (var i in extension) {
                if (extension.hasOwnProperty(i) && !obj.hasOwnProperty(i)) {
                    obj[i] = extension[i];
                }
            }
            return obj;
        }
    }
  8. How would you select the 3rd li element and retreive the value of it’s id attribute w/out selecting the li by id? *You can select it by index ```html

</ul>
```
- Answer:
```javascript
$('ul li').eq(2).attr('id');  
// OR
var item;                    
$.each($('ul li'), function(i) {                        
    if (i == 2) {                            
        item = $(this).attr('id');                        
    }                    
});    
```
  1. With jQuery, construct an array that has the values ["A", "B", "C", "D", "E", "F"] by getting the letters stored in the following html elements and pushing them into the array ```html
    B
    • D
    • E
    • C
    F
</div>
```

- Answer: 
```javascript
var letterArray = [];                       
letterArray.push($('.select-container').data("letter")); // Get letter "A"                     
var b = $('.select-container').contents().filter(function() { // Get letter "B"                  
    return this.nodeType === 3 && this.nodeValue.trim() !== '';            
}).text().trim();            
letterArray.push(b);             
var c = $('.select-wrapper ul').contents().filter(function() { // Get letter "C"                         
    return this.nodeType === 3 && this.nodeValue.trim() !== '';                    
}).text().trim();            
letterArray.push(c);             
letterArray.push($('#select-first').text()); // Get letter "D"              
letterArray.push($('.select-wrapper li').eq(2).text()); // Get letter "E"                         
letterArray.push($('.select-container > div:last-child span').text()); // Get letter "F"              
// Console log the array
console.log(letterArray);
```
  1. Write a script that generates a list of 150 div elements with random numbers as content. When the user clicks on one of the elements, first pop up a message that gives the random number, then remove that element from the list - Answer: html <!--HTML--> <div id="container"></div>
```javascript
// jQuery
for (var i = 0; i < 150; i++) {
    $("#container").append("<div>" + Math.random() + "</div>")
}
$('div', "#container").each(function() {
    $(this).on('click', function() {
        alert($(this).html());
        $(this).remove();
    })
});
```
  1. How do you check if an element is empty? - There are 2 ways to check if element is empty or not. We can check using ":empty" selector ```javascript // First way $(document).ready(function() { if  ($('#element').is(':empty')) {        //Element is empty } });
// Second way
$(document).ready(function() {
    if ($.trim($('#element').html()) ==  '') {
        // Element is empty
    }
});
```
  1. How do you check if an element exists or not in jQuery? - Using jQuery length property, we can ensure whether element exists or not javascript $(document).ready(function() { if ($('#element').length > 0) { // Element exists } });

  2. Given the following basic footer navigation

    Home | About Us | Deals | Contact Us
    

    What HTML/CSS would you use to achieve this?

    • Answer:
    <!--HTML-->
    <head>
        <title></title>
    </head>
    <body>
        <nav>
            <ul>
                <li>Home</li>
                <li>About Us</li>
                <li>Deals</li>
                <li>Contact Us</li>
            </ul>
        </nav>
    </body>    
    
    /* CSS */
    nav {
        position: absolute;
        bottom: 0;
    }
    ul {
        list-style: none;
    }
    li {
        float: left;
        padding: 11px;
    }
    li + li::before {
        content: "|";
        position: relative;
        left: -6px
    }
    
  3. How will you display different images based on the status being red, amber, or green? - Answer: Use the ng-switch and ng-switch-when directives as shown below ````html

</div>
````
  1. How will you initialize a select box with options on page load? - Answer: Use the ng-init directive html <div ng-controller="apps/dashboard/account" ng-switch  on="!!accounts" ng-init="loadData()">

  2. How will you show/hide buttons and enable/disable buttons conditionally? - Answer: Use the ng-show and ng-disabled directives ````html

    Save Release
</div>
````
  1. How will you loop through a collection and list each item? - Answer: Use the ng-repeat directive ````html
    </table>
    ````
    
    1. How will you add options to a select box? - Answer: Use the ng-options and ng-model directives ````html

      Client Id:

      Valuation Date (dd/mm/yyyy)
    </fieldset>
    ````
    
    1. How will you display inprogress revolving image to indicate that RESTful data is being loaded? - Answer: html <!--HTML--> <div ng-show="loading"> <img class="loading" src="portal/images/loading_32.gif" /> </div>
    ````javascript
    // Javascript
    $scope.loadReportData = function($http) { 
        $scope.loading = true;  // start spinng the image
         
        $http({  
            method: 'GET',
              url: propertiesService.get('restPath') + '/myapp/portfolio/' + $scope.clientId + '/' + dateService.userToRest($scope.reportDate),
              cacheBreaker: true  
        }).success(function(data, config) {  
            $scope.reportData = data;  
            portal.log('reportData: ', $scope.reportData);  
            $scope.loading = false;  // stop spinning the image
              
        }).error(function(data, status, headers, config) {  
            if (data.errorMsg != null) {   
                $scope.httpError = data.errorMsg;  
            }  
            else {  
                $scope.httpError = "Error retrieving data from " + errorService.getApacheErrorTitleMessage(status, data, config);    
            }  
            $scope.loading = false;  // stop spinning the image 
        });
    };
    ````
    
    1. Write a function declaration “sum()” which takes two numbers as arguments and returns the sum of those numbers - Answer: javascript function sum(a, b) { return a + b; }

    2. Write a function declaration "isVowel()" which takes a character (i.e. a string of length 1) and returns true if it is a vowel, false otherwise - Answer: javascript function isVowel(a) { if (a.length && a.length == 1) { a = String.fromCharCode(a.charCodeAt(0) | 32) if (a.match(/[aioue]/)) return true; } return false }

    3. Create a mechanism to print out all of the property names in this object. Do it in a way such that you will get the object foo, but you will not know the properties inside the object before hand

    ````javascript
    var foo = {
        first: "John",
        last: "Doe",
        getFullName: function() {
            return this.first + " " + this.last;
        }
    };
    ````
    
    - Answer:
    ````javascript
    for (var ele in foo) {
        if (foo.hasOwnProperty(ele)) {
            console.log(ele);
        }
    }
    ````
    
    1. What do you think will be the output of the printed calues in the console?

      var a = 5; 
      function runMe(a) {  
          console.log("a = ", a);  
          function innerRun() {   
              console.log("b = ", b);  
              console.log("c = ", c); 
          }   
          var b = 7;  
          innerRun();  
          var c = 8; 
      } 
      runMe(6);  
      for (var d = 0; d < 3; d++) {  
          setTimeout(function() {   
              console.log("d = ", d); 
          }, 100); 
      }
      
      • Answer:
      a = 6;
      b = 7;
      c = undefined;
      d = 3; (3 times)
      
    2. Loop through the color array and print each value to the console. Assume you do not know the amount of colors in the color array javascript var colors = [‘red, ‘yellow’, ‘green’, ‘blue’];                     for (var i = 0; i < colors.length; i++) {                         console.log(colors[i]);                     }

    3. Create a new javascript object with the keys of “fname” equal to your first name, “lname” equal to your last name, and “fcolors” equal to and array of 3 of your favorite colors. assign this object to a variable called “me” and log it to the console javascript var me = { "fname": "Riley", "lname": "Hilliard", "fcolors": ["blue", "green", "whitesmoke"] };                     console.log(me);  // OR var me = {};                     me.fname = "Riley";                     me.lname = "Hilliard";                     me.fcolors = ["blue", "green", "whitesmoke"];                     console.log(me);

    4. Loop through the “me” object and print each value to the console without assuming you know the keys. Extra bonus: print each color in a separate console.log() without assuming you know the key of “fcolors” (detect the array, and handle printing the values of the array javascript var me = { "fname": "Riley", "lname": "Hilliard", "fcolors": ["blue", "green", "whitesmoke"] };                     for (var key in me) {                         if (me.hasOwnProperty(key)) {                             if (me[key] instanceof Array) {                                 for (var i = 0; i < me[key].length; i++) {                                     console.log(me[key][i]);                                 }                             } else {                                 console.log(me[key]);                             }                         }                     }

    5. Write a function to remove every other element from an array without using additional arrays text For example: Given a = [5, 8, 1, 4, 9, 4, 2]. After runnning the function we should have a = [5, 1, 9, 2] - Answer: javascript function removeArrayElement(a) { for (var i = 0; i <= a.length/2; i++) { a[i] = a[i*2]; } a = a.slice(0, Math.round(a.length/2)); }

    6. Can you create an object using JS? How? - There are 3 ways to create a JavaScript object: they are 'Constructor functions', 'Literal notation', and 'Object.create() method' ```javascript // Constructor function function Car(make, model, year) { this.make = make; this.model = model; this.year = year; };

    // Literal notation
    var myHonda = {
        color: "red",
        wheels: 4,
        engine: {
            cylinders: 4,
            size: 2.2
        }
    };
    
    // Using Object.create method
    var Animal = {
        type: "Invertebrates", // Default value of properties
        displayType: function() { // Method which will display type of Animal
            console.log(this.type);
        }
    }
    var animal1 = Object.create(Animal);
    ```
    - Literal is a preferred option for name spacing so that your JavaScript code doesn't interfere (or vice versa) with other scripts running on the page and also if you are using this object as a single object and not requiring more than one instance of the object, whereas Constructor function type notation is preferred if you need to do some initial work before the object is created or require multiple instances of the object where each instance can be changed during the lifetime of the script
    
    1. How to creat an object with certain properit? Add a new property to an existed object? - Using prototypes: javascript function Box(color) { // Constructor this.color = color; } Box.prototype.getColor = function() { return this.color; } Hiding "color" (somewhat resembles a private member variable) javascript function Box(col) { var color = col; this.getColor = function() { return color; } } Usage javascript var blueBox = new Box("blue"); alert(blueBox.getColor()); // will alert blue var greenBox = new Box("green"); alert(greenBox.getColor()); // will alert green

    2. There are 3 pages in 1 Angular application, what can you do to achieve nested views?

    3. With the information from the above question, we have a scenario: in the first page, there are 2 tables, what can you do to share the same data to all the tables, how are you going to implement this?

    4. Follow the previous question, what if we need to fetch data from backend server, how are you going to implement this?

    5. Follow the previous question, on the second page, there is a table, what if some users want to show some columns while others don't, how do you impement it?

    6. Follow the previous question, how do you store the user's preference of showing or hiding these columns. What if we still want the preference to available when the user switch devices?

    account Difference Status
    {{account.accountCode}} {{account.difference | currency: ""}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment