ArticleZip > Jquery How To Grey Out The Background While Showing The Loading Icon Over It

Jquery How To Grey Out The Background While Showing The Loading Icon Over It

Have you ever visited a website and noticed how a loading icon appears while the page is loading? It's a handy visual cue that tells users to wait patiently for the content to appear. In this article, we will explore how to achieve this effect using jQuery by greying out the background while showing a loading icon over it.

To implement this feature, we first need to create the loading icon and the overlay background. You can design a loading icon using CSS or even use a pre-built one from icon libraries. Similarly, the overlay background can be created using CSS to cover the entire viewport.

Let's start by writing the jQuery code that will grey out the background and display the loading icon. First, we need to select the elements for the overlay and loading icon:

Javascript

var $overlay = $('<div id="overlay"></div>');
var $loader = $('<div id="loader"></div>');

Next, we will style these elements using CSS. Here's a simple example to get you started:

Css

#overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* Grey overlay */
  z-index: 999;
}

#loader {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /* Add your loading icon styles here */
}

Now, we can append these elements to the document body and display them when needed. Here's the jQuery code to show the overlay and loading icon:

Javascript

function showLoading() {
  $('body').append($overlay);
  $('body').append($loader);
}

function hideLoading() {
  $overlay.remove();
  $loader.remove();
}

To use these functions, you can call `showLoading()` when you want to display the loading icon and `hideLoading()` when the content has finished loading.

Remember to adjust the CSS styles and positioning to fit your website's design. You can customize the overlay color, loading icon, and animation to match your brand's aesthetic.

In conclusion, adding a loading icon with a greyed-out background using jQuery can enhance the user experience on your website by providing visual feedback during content loading. By following the steps outlined in this article and customizing the styles to suit your website's design, you can create a professional and engaging loading experience for your users. Give it a try and impress your visitors with a sleek loading animation!