How To Put Loading To Some Element When Waiting The Data Processed - Save My Knowledge
Monday, January 9, 2017

How To Put Loading To Some Element When Waiting The Data Processed

Hi, I want to share how to put simple loading bar to some specific element like this on our webpage:
Just a simple code and simple usage.
I am using jQuery and font-awesome to create this thing, so prepare your jQuery and font-awesome first.

Here is the code:


Javascript:
function startLoadingElement(element, text) {
  text= (typeof text== 'undefined' ? "" : " " + text);
  stopLoadingElement(element);
  element.append("<div class='loading-element'><div class='loading-element-content'><span class='loading-element-content-border'><em class='loading-element-content-image fa fa-lg fa-spinner fa-spin'></em>"+text+"</span></div></div>");
}

function stopLoadingElement(element) {
  if(element.has(".loading-element").size() > 0) {
    element.find(".loading-element").remove();
  }
}
CSS:
.loading-element {
  width: 100%;
  height: 100%;
  top: 0px;
  left: 0px;
  position: absolute;
  display: block;
  opacity: 0.9;
  background-color: white;
  border: 1px solid #ccc;
  z-index: 99999;
}

.loading-element-content {
  position: absolute;
  top: calc(50% - 8.5px);
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  left: 0;
  right: 0;
  z-index: 100;
}

.loading-element-content-border {
  border: 1px solid #ccc;
  padding: 2px 4px;
}

.loading-element-content-image {
  margin-top: 2px;
}

How to use:

Just call this function on javascript
startLoadingElement(param1, param2)
param1: The element you want to cover with the loading (The element is get from jQuery)
param2: The string you want to shown when the loading is show (optional, you can leave it empty)
Example: I want to put loading screen on my <body> with string "Please wait", the code should be
startLoadingElement($("body"), "Please wait")
Another example: I want to put loading screen on my <div> with id="container" without any text on it, the code should be
startLoadingElement($("#container"))
And if you want to set loading 2 element or more, you just need to select it on the jquery, the code should be
startLoadingElement($("#container, .table-container"))
To remove the loading we've set, here is the code
stopLoadingElement(param1)
param1: The element you want to remove the loading (The element is get from jQuery)
Example: I want to remove loading screen on my <body>, the code should be
stopLoadingElement($("body"))

That's all, pretty ease to use, right? 😊