Showing posts with label Vanilla. Show all posts
Showing posts with label Vanilla. Show all posts

5/2/19

How To Attach 'AddEvenlistener' Correctly

One of my recent tasks was - to implement the site side menu list (using vanilla javascript), and I was very glad to take a challenge - and practice my vanilla skills. I like to use vanilla - since I think it will replace in short future all the frameworks like react & angular...
Yes it sad (because I big fun of frameworks) but lets face the truth - javascript (or ECMASCRIPT) is developing very fast and already doing most of things we needed frameworks for...

Lets Focus, The Menu

So, menu is the very simple one, with links to all site subpages, but the goal is - that clicks on items should be handled only by javascript


<ul class="menu">
  <li><a href="javascript: void(0)">1 menu</a></li>
  <li><a href="javascript: void(0)">2 menu</a></li>
  <li><a href="javascript: void(0)">3 menu</a></li>
</ul>

For simplicity sake - lets say that "handle" means - to print the textContent of clicked item to the console.

First Try

So my first solution was to capture all the 'a' elements using "querySelectorAll" native method, and attach listeners to each of the using "forEach" loop:


document.querySelectorAll('ul.menu a')
.forEach(menuItem => menuItem.addEventListener('click', ({target}) => {
  console.log(target.textContent); // printing '1 menu' when first menu clicked 
}))

Second Look

After giving the code a second look - I suddenly figured out the things may be done much more simply - by attaching the listener only to parent 'ul' element:


document.querySelector('ul.menu').addEventListener('click', ({target}) => {
  console.log(target.textContent)
})

The advantage (except from simplicity) of this attitude is that instead of many listeners we using only one (which is much more performant)

Conclusion

The main reason we can use only one listener for many elements is the advantage of using "target" - the way to identify the element user clicked inside the parent element. The important thing here - is to know that event argument has also "currentTarget" property, and unlike "target"(which set to element the user actually clicked upon) - the "currentTarget" set to element the listener attached to

2/24/19

SPA with vanilla javascript

It is 2019 now and javascript (es2019) is much more powerful than in the old days.
The following article is encourages me to try and see what can be gone when you using only plain js:
For example - to display a list of GitHub users from previous post it is anough to use the native javascript "map" :

document.querySelector('#container')
  .innerHTML = users.map(({login, count}) => `<li>${login} - <span>${count}</span></li>`).join(''); 
As result - the list with usernames and repos number will created on the page.
For completion of the picture we can add the "next" button that will display the next page:

 <button onClick="go()">next</button>
 <span>page:
    <i id='currPage'></i>
 </span>
 <ul id='container'>
 </ul>
The code for all this UI logic will be no more than 20 lines:

// getting data for page & displaying
function getPage(currentPage = -1) {
  currentPage++;
  // display loadign animation
  showLoader();
  
  getData(currentPage * 10).then((users) => {
     // display the number of page 
     updatePage(currentPage + 1);
     document.querySelector('#container')
       .innerHTML = users.map(({login, count}) => `<li>${login} - <span>${count}</span></li>`).join(''); 
  });
  return currentPage;
}

// display loading animation
function showLoader() {
  const img = '';
  document.querySelector('#container').innerHTML = img;
}

// displayes page number
function updatePage(page) {
  document.querySelector('#currPage').innerText = page;
}

// goes to nex page
function go() {
  page = getPage(page);
}

// getting page first time
page = getPage();
This is very minimalistic, but yet - kind of SPA!

3/20/18

Creating Javascript Router With Vanilla Javascript

What is router?
Router is a way to get different content in response to changes of url.
example:

That way it easy to memorize the url, and also you are able to navigate exact to product you need by the link (/vehicle/297 will lead you to SV650).
But what it means when speaking about JavaScript? Can JavaScript change the url without triggering full refresh of page?

Yes You Can

 It appears that javascript can change the url with HTML5 feature:

window.history.pushState("object or string", "sv650", "/sv650");



But How To Subscribe To Url Changes?

Yes, there is another HTML5 feature for it:
You can subscribe to 'pushstate' event:


window.addEventListener('popstate', (e) => {
  ...
});

Here is stackblitz project demonstrating routing in action

Summary

In this post you have learned that all 'Router' thing is actually very simple, and can be achieved with few pure javascript commands...
If you need more customizations like 'hash' Here is navigo vanilla javascript router...

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...