Intermediate JavaScript: Building Frontend Components Educative Quiz Answers

Get Intermediate JavaScript: Building Frontend Components Educative Quiz Answers

Learn to apply your introductory knowledge of HTML, CSS, and JavaScript to build beautiful, real-world components. In this course, you’ll go through the process of developing several complex components, including:

– eBay’s dropdown menu

– Gmail’s auto-validating form

– Google’s main autocomplete enabled search

– Twitter’s infinitely scrolling list

– Medium’s tooltips You’ll learn how to approach common frontend challenges, what questions to ask yourself, how to design solutions once you’ve thought of them, how to debug and work with mistakes, and more.

The end-goal is to empower you to look at anything you see on a website and be able to say, “I can build that!”

Enroll on Educative

Quiz 1: Basic HTML Code

Q1. When is it appropriate to hardcode data into HTML?

  • The data is different depending on the user
  • The data is updated infrequently
  • The size of the data set is large
  • The data appears on every page

Quiz 2: Submenu

Q1. Which division of groups is best suited for the submenu?

  • Three divs, one for each column and one for the picture
  • One div for the column headers, one div for each row, one div for the image portion
  • One div for the text portion and one div for the image portion
  • One div for the text portion, two inner divs for each column, and one div for the image portion

Quiz 3: Implementing the Behavior of Dropdown Menu

Q1. Why is the above line wrong?

  • It uses the wrong value of menuItem
  • It calls the function at the wrong moment
  • It doesn’t bind anything to the onmouseenter function

Challenge 1: Extending the Submenu Functionality

Solution:
const HOST = 'server.com/';

function populateCategories(category) {
  const activeMenuItemName = activeMenuItem.children[0].innerHTML;
  api.get(HOST + 'categories', {category, menuItem: activeMenuItemName}, function(categories) {
    let newCategories = '';
    for (const category of categories) {
      const categoryElement = `
        <li class="menu__sub__categories__item">
          <a href="#" class="menu__sub__categories__item__link">${category}</a>
        </li>
      `;
      newCategories += categoryElement;
    }
    const categoriesElement = document.getElementsByClassName(`menu__sub__categories__items--${category}`)[0];
    categoriesElement.innerHTML = newCategories;
  });
}

function showSubmenu() {
  const submenu = document.getElementsByClassName("menu__sub")[0];
  submenu.style.display = "block";

  populateCategories('top');
  populateCategories('additional');
}

function hideSubmenu() {
  const submenu = document.getElementsByClassName("menu__sub")[0];
  submenu.style.display = "none";
}

let activeMenuItem = null;

function onMenuItemMouseEnter(item) {
  if (activeMenuItem) {
    activeMenuItem.classList.remove("menu__main__item--active");
  }
  activeMenuItem = item;
  item.classList.add("menu__main__item--active");
  showSubmenu();
}

const menuItems = document.getElementsByClassName("menu__main__item");
for (const menuItem of menuItems) {
  menuItem.onmouseenter = () => onMenuItemMouseEnter(menuItem)
}

const menu = document.getElementsByClassName("menu")[0];
menu.onmouseleave = hideSubmenu;

// Server

function getCategories(data) {
  if (data.category == 'top') {
    if (data.menuItem == 'Motors') {
      return [
        'Car',
        'Motorcycle',
        'Plane',
        'Trucks',
        'Wheels'
      ];
    }
    if (data.menuItem == 'Fashion') {
      return [
        'Women\'s tops',
        'Men\'s tops',
        'Jeans',
        'Hats'
      ];
    }
    return [
      'Server apple',
      'Server banana',
      'Server pear',
      'Server orange'
    ];
  }
  if (data.category == 'additional') {
    if (data.menuItem == 'Motors') {
      return [
        'Tires',
        'Windshields',
        'Ski racks',
        'Doors',
        'Windows'
      ];
    }
    if (data.menuItem == 'Fashion') {
      return [
        'On sale',
        'Red stuff',
        'Gucci',
        'New Arrivals'
      ];
    }
    return [
      'Server square',
      'Server circle',
      'Server oval',
      'Server diamond'
    ];
  }
  return [];
}

const endpoints = {
  "/categories": {
    "get": getCategories
  }
}

function getFunction(url, data, callback) {
  const domain = url.substring(0, url.indexOf("/"));
  const endpoint = url.substring(url.indexOf("/"), url.length);

  callback(endpoints[endpoint]["get"](data));
}

const api = {
  get: getFunction
};

function deactivateMenuItem() {
  activeMenuItem.classList.remove("menu__main__item--active");
}
 
const submenu = document.getElementsByClassName("menu__sub")[0];
submenu.onmouseleave = deactivateMenuItem;

Quiz 4: Examining Google’s Autocomplete Functionality

Q1. What scenario would we most likely want the client to cache results?

  • The responses are large in size
  • The responses include sensitive data that we don’t want to be repeated
  • The responses vary depending on time (requests made at time T may give different results than requests made at time T+1)
  • There are multiple responses given for the same request

Quiz 5: Building a Server Endpoint for Autocomplete

Q1. Will this work for our development purposes?

  • Yes, it gives a list of strings which is all we need
  • No, we want results that are prefixed with data we passed
  • No, we need more structured data to include the extra information in the edge case that there multiple results of the same string
  • B and C

Quiz 6: Building a Server Endpoint for Autocomplete

Q1. Which edge case will not be fully tested with this server code?

  • Case 1: When there exists multiple results of the same string, detail is added after a hyphen
  • Case 2: Results seem to assume for some autocorrect, and therefore won’t always be prefixed by what’s in the input bar
  • Case 3: Results are shown for every character input, including backspace, and only the most recent is shown
  • Case 4: If I input something that the server’s already given me a response for, the client will still make another request
  • Case 5: The buttons merge with the autocomplete results

Quiz 7: Displaying Autocomplete Suggestions

Q1. Why did we get this output?

  • Our functions are generating “[object Object]” as suggestions
  • We’re printing a JavaScript object whose string representation is “[object Object]”
  • The API library has converted the responses to objects
  • Our event listener is converting data to objects

Quiz 8: Perfecting the Position

Q1. Would setting the width a hardcoded value of 10rem for the element in Javascript be a better option?

  • Yes, we need to have the element’s top and left set before we put it on the DOM, and the only way to do that is to have the width in Javascript.
  • Yes, keeping the variable in Javascript is more accurate.
  • No, it couples the CSS and JavaScript too closely, if the width changes, we need to change it in multiple places.
  • No, rem is only understood if defined in CSS.

Quiz 9: Adding Animations

Q1. Why do you think this is happening?

  • It’s traveling from the previously set top and left position
  • We’re using the same JavaScript object for two positions
  • The transition shouldn’t apply to positions

Quiz 10: Test Driven Development

Q1. Which of the following is not a useful test?

  • Given an email input of “asdf,” check that the validating function returns false.
  • When a user clicks submit with the name fields blank, check that no submission occurs.
  • When a user blurs on an input and leaves it empty, check that an error message is shown.
  • They’re all useful tests.

Quiz 11: Unique Errors for Each Field

Q1. How do you know which validation rule to apply?

  • Infer from the order. For example, we know the first one is firstName, so we apply the validation rule for names
  • Infer from class name of event target. For example, if it’s signup__field__input--firstname, we know to apply the name validation
  • Infer from the placeholder of the target
  • Infer from the accessibility aria-label

Quiz 12: Validation of User Input with Regex

Q1. Which regex will enforce an input with the rule that only allows numbers of length 4?

  • /^{0-9}+$/
  • /^[0-9]+4$/
  • /^[4]{0-9}$/
  • /^[0-9]{4}$/

Quiz 13: Building an HTML Template for Infinite Lists

Q1. Which grouping is reasonable?

  • A
  • B
  • C
  • D
  • All the above

Quiz 14: Server Client Communication

Q1. What information would you add to request tweets so that there’s enough to satisfy our requirements?

  • lastTweetId – the unique ID of the tweet that was at the bottom of the results
  • timeLastRequested – the timestamp to the millisecond of when the last request was
  • listOfTweetIds – the list of tweet IDs that we have
  • Two of the above

Quiz 15: Autopopulation

Q1. Which change do you think works best?

  • Call setPending when response length is 0, add a setTimeout to call setReady after some delay
  • Add a third state like backoff, and have the onScroll function return immediately given that state and add a setTimeout to call setReady after some delay
  • Add a setTimeout when the response length is 0 to call the onScroll function, which will load more things only after a delay

Challenge 2: Autopopulation

Solution:
const DEFAULT_PAGE_SIZE = 5;
const DEFAULT_SORT_ORDER = 'recent';

const States = {
  PENDING: 'pending',
  READY: 'ready',
  BACKOFF: 'backoff'
};

let componentState = States.READY;

function isComponentPending() {
  return componentState === States.PENDING;
}

function setPending() {
  componentState = States.PENDING;
  document.body.appendChild(loadingElement);
}

function setReady() {
  componentState = States.READY;
  document.body.removeChild(loadingElement);
}

function setBackoff() {
  componentState = States.BACKOFF;
  document.body.removeChild(loadingElement);
}

let lastTweetId = null;

const loadingElement = document.createElement('div');
// Give it the same style
loadingElement.classList.add('tweet');
loadingElement.innerHTML = `
  Here I am... Loading...
  <img class="loading__image" src="http://educative.io/udata/1m5lkL7p9Q0/dog.jpeg" />
`;

function onNewTweets(data) {
  if (data.length <= 1) {
      setBackoff();
      setTimeout(() => setReady(), 2000);
  } else {
  setReady();
  let tweetsHTML = '';
  for (const tweetResponse of data) {
    const tweet = createTweet(tweetResponse.tweet);
    tweetsHTML += tweet;
    lastTweetId = tweetResponse.id;
  }
  document.body.innerHTML += tweetsHTML;
  }
}

function hydrate() {
  const params = {
    pageSize: DEFAULT_PAGE_SIZE,
    sortOrder: DEFAULT_SORT_ORDER
  }
  api.get(HOST + 'tweets', params, onNewTweets);
  setPending();
}

loadTestData();
hydrate();

function onScroll(event) {
  if (isComponentPending()) {
    return;
  }
  const scrolledTo = window.innerHeight + window.pageYOffset;
  const scrollLimit = document.body.offsetHeight;
  const scrollThreshold = 30;

  if (scrollLimit - scrolledTo <= scrollThreshold && componentState != 'backoff') {
    const params = {
      pageSize: DEFAULT_PAGE_SIZE,
      sortOrder: DEFAULT_SORT_ORDER,
      lastTweetId
    }
    api.get(HOST + 'tweets', params, onNewTweets);
    setPending();
  }
}

window.addEventListener('scroll', onScroll);
</script>

Quiz 16: Resourcing

Q1. Which idea doesn’t seem possible?

  • A web app that lets me fly a drone with hand movements
  • A web app that lets you send text messages to control the mouse
  • A web app that lets you talk directly to someone on the other side of the world
  • A web app that can crash your browser (or computer)
Conclusion:

I hope this Intermediate JavaScript: Building Frontend Components Educative Quiz Answers would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *