URL Shorten Worker: Bootstrap UI & Code Optimization

Source code GitHub: https://github.com/crazypeace/Url-Shorten-Worker

Setup tutorial: https://zelikk.blogspot.com/2022/07/url-shorten-worker-hide-tutorial.html


Effect:



Apply Bootstrap List group for beautification

Reference:

Bootstrap List group

https://getbootstrap.com/docs/4.0/components/list-group/

Add class attribute when JS adds elements

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Implementation:

In index.html, set the class attribute of ul to list-group

    classs="list-group" id="urlList"> 

    In main.js, set the class attribute of li to list-group-item

    let urlList = document.querySelector("#urlList")
    let child = document.createElement('li')
    let text = document.createTextNode(shortUrl + " " + longUrl)
    child.appendChild(text)
    child.classList.add("list-group-item")
    urlList.append(child)

    --------

    Code optimization

    Remove load.js, merge the code into main.js. Extract the code that adds li to the ul list into a function, and call it both when the page loads and when a short link is added.

    function addUrlToList(shortUrl, longUrl) {
      let urlList = document.querySelector("#urlList")
      let child = document.createElement('li')
      let text = document.createTextNode(shortUrl + " " + longUrl)
      child.appendChild(text)
      child.classList.add("list-group-item")
      urlList.append(child)
    }

    --------

    Pre-search localStorage in the long URL text box

    Reference:

    Text box content change event

    https://www.w3schools.com/jsref/event_oninput.asp

    Implementation:

    Add the oninput event to the long URL text box to call loadUrlList()
    oninput="loadUrlList()">

     Add judgment for the long URL text box content in loadUrlList()

    // Long URL in the text box
    let longUrl = document.querySelector("#longURL").value
    console.log(longUrl)

    // Iterate through localStorage
    let len = localStorage.length
    console.log(+len)
    for (; len > 0; len--) {
        let keyShortURL = localStorage.key(len - 1)
        let valueLongURL = localStorage.getItem(keyShortURL)
        // If the long URL is empty, load all localStorage
        // If the long URL is not empty, load matching localStorage
        if (longUrl == "" || (longUrl == valueLongURL)) {
          addUrlToList(keyShortURL, valueLongURL)
        }
    }

    --------

    GitHub: https://github.com/crazypeace/Url-Shorten-Worker

Comments