Categories
JavaScript Answers

How to Loop Through a Plain JavaScript Object?

JavaScript objects are dynamically created by adding properties to them.

Therefore, we may have to loop through its properties with a loop to get the values.

In this article, we’ll look at how to loop through a plain JavaScript object.

Object.keys

The Object.keys method returns an array of all non-inherited string property keys of an object.

To use it, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}
for (const key of Object.keys(obj)) {
  console.log(key, obj[key])
}

We use the for-of loop to loop through the array of keys returned by Object.keys .

Then we can access the value by passing the key into the square brackets after obj .

So we see:

a 1
b 2
c 3

logged.

Object.values

We can just loop through the values of an object with the Object.values method.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

for (const value of Object.values(obj)) {
  console.log(value)
}

Object.values return an array with all the properties values of an object, so we can use the for-of loop to log the property values.

And so we get:

1
2
3

in the console.

Object.entries

Also, we can use the Object.entries method to return an array with arrays of key-value pairs.

To do this, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value)
}

We destructure the key and value from each array entries returned by Object.entries .

Then we can log them in the loop body.

And we get the same result as we did in the previous example.

Loop Through Nested Objects

To loop through a nested object, we can create a function that calls itself to loop through their properties at each level of the object.

To do this, we write:

const obj = {
  a: 1,
  b: 2,
  c: {
    d: {
      e: 4
    },
    f: 5
  }
}
const loopNestedObj = obj => {
  for (const [key, value] of Object.entries(obj)) {
    console.log(key, value)
    if (typeof value === 'object' && value !== null) {
      loopNestedObj(value)
    }
  }
}

loopNestedObj(obj)

We create the loopNestedObj function that takes an obj object.

Inside the function, we have the same loop as in the previous example.

But we have an if block to check the value ‘s data type to see if it’s an object.

If it is, then we call loopNestedObj to loop through its content.

The expression typeof value === ‘object’ && value !== null is needed to check if value is an object since typeof null is also 'object' .

Therefore, we need both checks to check for an object.

Conclusion

We can traverse an object with the for-of loop and various static object methods provided by JavaScript.

Categories
JavaScript Answers

How to Listen to Events on Dynamically Created Elements with JavaScript?

Many items in a web page are dynamically created with JavaScript.

This means that we’ve to listen to events that are emitted by them so that we can use them to do something other than display content statically.

In this article, we’ll look at how to listen to events on elements that are created dynamically with JavaScript.

Event Delegation

We can listen to events emitted on the container element that has the dynamically created elements.

In the event listener, we can check which item is emitting an event do the stuff we want depending on the element emitting the event.

This is possible because events emitted by an element bubble up to its parent and ancestor elements all the way to the body and html elements unless we stop it manually.

Therefore, the body element’s event listener will pick up events from all its descendant elements if we allow them to propagate.

For instance, we can write the following HTML:

<div>

</div>

And create then write the following JavaScript to listen to click events emitted by the dynamically created p elements:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.className = i % 2 === 1 ? 'odd' : 'even'
  p.textContent = 'hello'
  div.appendChild(p)
}

document.addEventListener('click', (e) => {
  if (e.target.className.includes('odd')) {
    console.log('odd element clicked', e.target.textContent)
  } else if (e.target.className.includes('even')) {
    console.log('even element clicked', e.target.textContent)
  }
});

In the code above, we get the div element with document.querySelector .

Then we use a for loop to add p elements inside the div 100 times.

We set the className of the element to set the value of the class attribute.

textContent has the value of the content of the p element.

Then we call appendChild on the div to add the p element inside the div.

Then to listen to click events on the p elements we just added, we listen to the click of document , which is the body element.

We call addEventListener to add the click listener to the body element.

Then we pass in a callback as the 2nd argument of addEventListener .

The e parameter is the event object.

It has information about the original element that emitted the event.

We get the element that originally emitted the event with the e.target property.

So we can get the value of the class attribute of the element with the e.target.className property.

And we get the value of the textContent property with the e.target.textContent property.

Conclusion

We can listen to events emitted by dynamically created HTML elements with event delegation.

We just listen to events from the ancestor of the elements that emit the events and then check which element emitted the event in the callback.

Categories
JavaScript Answers

How to Scroll to the Top of the Page with JavaScript?

Sometimes, we need to scroll to the top of a web page programmatically.

In this article, we’ll look at how to scroll to the top of the page with JavaScript.

Scroll to the Top of the Page with JavaScript

We can scroll to the top of the page with JavaScript with the window.scrollTo method.

For instance, if we have the following HTML code:

<div>

</div>
<button>
  scroll to top
</button>

Then we can create a page of content with JavaScript and make the button scroll to the top of the page by writing:

const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  window.scrollTo(0, 0);
})

We get the div with querySelector .

Then we have a for loop which creates a p element with document.createElement .

And we set textContent to it.

And then we call appendChild to append the p element to the div.

To make the button scroll the page to the top when we click it, we call addEventListener on the button.

In the callback, we call window.scrollTo with the x and y coordinates to scroll to respectively.

Smooth Scrolling Animation

We can add smooth scrolling animation when we’re scrolling.

To do this, we pass in an object to scrollTo instead.

For instance, we can write:

const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

button.addEventListener('click', () => {
  window.scrollTo({
    top: 0,
    left: 0,
    behavior: 'smooth'
  });
})

We pass in an object with the top and left properties to set the x and y coordinates to scroll to respectively.

Also, we set the behavior property to 'smooth' to make the scrolling animation smooth.

This is better making the page jump straight to the top without the behavior options as we have in the first example.

Conclusion

We can use the window.scrollTo method to make a page scroll to the top with JavaScript.

We can set the location to scroll to and whether animation is shown or not during scrolling.

Categories
React Projects

Create an RSS Reader with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create an RSS reader with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app rss-reader

with NPM to create our React project.

Create the RSS Reader

To create the RSS reader, we write:

import React, { useState } from "react";

export default function App() {
  const [rssUrl, setRssUrl] = useState("");
  const [items, setItems] = useState([]);

  const getRss = async (e) => {
    e.preventDefault();
    const urlRegex = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/;
    if (!urlRegex.test(rssUrl)) {
      return;
    }
    const res = await fetch(`https://api.allorigins.win/get?url=${rssUrl}`);
    const { contents } = await res.json();
    const feed = new window.DOMParser().parseFromString(contents, "text/xml");
    const items = feed.querySelectorAll("item");
    const feedItems = [...items].map((el) => ({
      link: el.querySelector("link").innerHTML,
      title: el.querySelector("title").innerHTML,
      author: el.querySelector("author").innerHTML
    }));
    setItems(feedItems);
  };

  return (
    <div className="App">
      <form onSubmit={getRss}>
        <div>
          <label> rss url</label>
          <br />
          <input onChange={(e) => setRssUrl(e.target.value)} value={rssUrl} />
        </div>
        <input type="submit" />
      </form>
      {items.map((item) => {
        return (
          <div>
            <h1>{item.title}</h1>
            <p>{item.author}</p>
            <a href={item.link}>{item.link}</a>
          </div>
        );
      })}
    </div>
  );
}

We have the rssUrl state that stores the RSS feed URL we enter.

And the items state store the feed items which we’ll get.

Then we define the getRSS function to get the RSS feed items when we click submit.

Next, we call e.preventDefault() to let us do client side submission.

Then we check if the rssUrl value is a valid URL string.

If it is, then we make a GET request with fetch to the RSS feed via a CORS proxy.

We use the allOrigins API to let us make cross-domain requests to the given feed.

We need this since cross-domain communication from the browser isn’t allows with most feeds.

We get the contents property from the object.

Then we parse the XML string with the DOMParser instance’s parseFromString method.

The first argument is the XML string.

And the 2nd argument is the content-type string.

feed is the XML DOM object with the whole XML tree.

Then we use querySelectorAll to get all the item nodes.

And then we use the spread operator to spread the items Node list to an array.

Then we can call map on it to select nodes inside the item nodes with querySelector and return an object with the innerHTML values.

We call setItems to set the items state.

Below that, we have the form with the onSubmit prop set to getRSS to let us run the function when we click on the input with type submit .

Inside the form, we have an input with the onChange prop set to a function that calls setRssUrl to set the inputted value as the value of the rssUrl state.

e.target.value has the inputted value.

value is set to rssUrl so that we can see the inputted value.

Below the form, we render the items into divs with the map method.

Conclusion

We can create an RSS reader easily with React and JavaScript.

Categories
Vue

Create an RSS Reader with Vue.js and JavaScript

Vue.js is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create an RSS reader app with Vue.js and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create rss-reader

and select all the default options to create the project.

Create the RSS Reader

To create the RSS reader, we write:

<template>
  <div id="app">
    <form @submit.prevent="getRss">
      <div>
        <label> rss url</label>
        <br />
        <input v-model="rssUrl" />
      </div>
      <input type="submit" />
    </form>
    <div v-for="item of items" :key="item.title">
      <h1>{{ item.title }}</h1>
      <p>{{ item.author }}</p>
      <a :href="item.link">{{ item.link }}</a>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      rssUrl: "",
      items: [],
    };
  },
  methods: {
    async getRss() {
      const urlRegex = /(http|ftp|https)://[\w-]+(.[\w-]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?/;
      if (!urlRegex.test(this.rssUrl)) {
        return;
      }
      const res = await fetch(
        `https://api.allorigins.win/get?url=${this.rssUrl}`
      );
      const { contents } = await res.json();
      const feed = new window.DOMParser().parseFromString(contents, "text/xml");
      const items = feed.querySelectorAll("item");
      this.items = [...items].map((el) => ({
        link: el.querySelector("link").innerHTML,
        title: el.querySelector("title").innerHTML,
        author: el.querySelector("author").innerHTML,
      }));
    },
  },
};
</script>

We have a form with a form field to let us enter the RSS feed’s URL.

We bind the inputted value to the rssUrl reactive property.

In the form element, we listen to the submit event, which is triggered when we click on the input button with type submit .

The prevent modifier lets us do client-side submission instead of server-side.

Below that form, we use the v-for directive to render the RSS data, which we store in the items reactive property.

In the script, we have the getRss method.

The method first checks if rssUrl is valid.

If it is, then we call fetch to make a request to get the data from the RSS feed.

We use the allOrigins API to let us make cross-domain requests to the given feed.

We need this since cross-domain communication from the browser isn’t allows with most feeds.

The request has the contents property with the XML RSS feed content.

Then we use the parseFromString method from the DOMParser constructor to let us parse the XML string.

We pass in the XML string as the first argument.

And the 2nd argument has the content type of what we’re parsing.

It returns the XML tree DOM object.

This means we can use methods like querySelectorAll to select nodes.

Then we can select the item nodes with querySelectAll .

And then we use the spread operator to spread the items from the Node list to an array.

Next, we call map to return objects with the content of the nodes we select with querySelector .

Now in the template, the divs below the form should render with the RSS feed content.

Conclusion

We can create an RSS feed easily with Vue.js and JavaScript.