What is the best way to align an image in a particular div based on the current position of the viewport

I want to add a sleek animation while loading content using ajax. My goal is to display an icon while the "Content" div is reloading, but I'm not sure if this can be achieved with just CSS.

The icon needs to:

  1. Always be horizontally centered within the "Content" div
  2. Be vertically centered within the visible part of the content
  3. Remain vertically centered within the visible part of the content throughout a sliding animation that hides the Menu

If vertical centering based on the visible part of the content isn't possible, I'm fine with centering the image according to the browser's viewport.

[EDIT]:

Check out my fiddle here: http://jsfiddle.net/QWB9x/74/. The section that probably needs adjusting is:

.loading #img_loading {
    position: fixed;
    top: 50%;
    left: 50%;
    display: block;
}

Answer №1

This solution has proven to be the most effective for me :)

function fetchNewData(){
 $(".loaderCont").removeClass("loading")
}

$(document).ready(function () {

 $("#hide_button").on("click", function () {
      $(this).closest(".bottom").toggleClass("left_hided");
      $(".loaderCont").toggleClass("left_hided2");
 });

 $("#filter1,#filter2,#filter3,#filter4").on("click", function() {
     $(".loaderCont").addClass("loading");
     setTimeout(fetchNewData, 2000);
 });
});

CSS:

.header {
    background-color: Green;
    width: 100%;
    margin-bottom: 20px;
     height: 100px;
}
.left {
    background-color: Red;
    float: left;
    width: 100px;
}
.left_hided .left{
    margin-left: -85px;
}
.right {
    background: Aqua url("http://i.imgur.com/ifyW4z8.png") 50% repeat-y;
    width: calc(100% - 140px);
    float: right;
}

.left_hided .right{
     width: calc(100% - 55px);
}

input{
    float:right;
}

.loaderCont {
    background-color: rgba(255, 0, 0, 0.6);
    height: 100%;
    width: calc(100% - 140px);
    position: fixed;
    right: 0;
    top: 0;
    z-index: -1;
}

.left_hided2 {
     width: calc(100% - 55px);
}

#loader {
    background: url(https://i.sstatic.net/FhHRx.gif) no-repeat center center;
    position: relative;
    top: calc(50% - 16px);
    left: calc(50% - 16px);
    display: block;
     height: 32px;
     width: 32px;
}

.loading {
    z-index: 9001;
}

JSFiddle: http://jsfiddle.net/ZRwzr/1/

Answer №2

To meet your specific requirements, JavaScript must be used to determine the precise placement of the loading image over the visible section by utilizing a fixed position div. The image should be repositioned whenever the user scrolls or resizes the window to ensure it remains in the desired location.

$(window).scroll(function() {
    scrolling();
});

$(window).resize(function() {
   scrolling(); 
});

scrolling();

function scrolling() {
    var windowHeight = $(window).height();
    var scrollTop = $(window).scrollTop();
    var offsetTop = $('#thediv')[0].offsetTop;
    var offsetHeight = $('#thediv')[0].offsetHeight;

    var offsetWidth = $('#thediv')[0].offsetWidth;

    var top = offsetTop - scrollTop;
    top = top < 0 ? 0 : top;

    var bottom = (scrollTop + windowHeight) - (offsetHeight + offsetTop);
    bottom = bottom < 0 ? 0 : bottom;

    $('.image').css('top', top);
    $('.image').css('bottom', bottom);
    $('.image').css('width', offsetWidth);
}

It's important to note that if the width of the div is changed, the scrolling() function must be called again to recalculate the positioning.

The loading image has been added as a background image to the fixed div, allowing CSS to center it with ease.

.image {
    position: fixed;
    text-align:center;
    background-image:url('https://i.sstatic.net/FhHRx.gif');
    background-repeat:no-repeat;
    background-position:center center;
    background-color:rgba(255,255,255,.4);
}

Check out the JSFiddle for a demonstration: http://jsfiddle.net/QWB9x/89/

Answer №3

To position a loader, you don't need complex scripting - simple CSS will do the trick.

Simply make the loader relative to its parent, give it a height and width, and add the following CSS:

.loader{
    position: relative;
    top: -half of the height;
    left: -half of the width;
    margin-top: 50%;
    margin-left: 50%;
}

This method is compatible with all devices.

Answer №4

example using z-index property:

 <div style="z-index:100;">loading image</div> 

Answer №5

.loading #img_loading {
    position: fixed;
    top: 50%;
    left: calc(50% + 55px);
    display: block;
}

To further enhance the solution, you can use JavaScript to update the left dynamically based on your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I style the inner div by adding a class to the first div?

In my project, I have a list of elements that are generated dynamically, all styled the same way but with different content. The first element has a specific styling, and if it doesn't render, I want the second element to inherit that styling. < ...

Looking to create a format for displaying short comic strips in a grid pattern

I am struggling to create an image grid for my small comics. I want to have 2 columns and 3 rows, but all the divs end up in the same place. I tried using display: flex, but it didn't work as expected. Additionally, I want the grid to be responsive, b ...

Guidance on displaying values from one PHP file in another PHP file

Is it possible to achieve this scenario? I have two files, named main.php and submenu.php. In main.php, I have the main menu defined as follows: In another file called submenu.php, I have a list structured like this: <ul> <li>1</li> &l ...

Steps to reinitialize the error code after removal from the roster

Currently, I am working on creating a series of textboxes and dropdown menus using jQuery. So far, the add function is functioning smoothly without any glitches. However, my issue lies within the delete function. It works well when deleting sequentially, ...

Tips for incorporating dimensions from ajax svg text with jquery:

When receiving SVG content through AJAX jQuery, the width and height are missing. To solve this issue, we can add the width and height from the AJAX jQuery response. Code: $jd.ajax({ type: "POST", data: item, ...

Creating expandable card components with React and CSS using accordion functionality

I am currently working on creating a card that will expand its blue footer when the "view details" link is clicked to show lorem text. However, I am encountering an issue where the blue bottom of the card does not expand along with the lorem text. You can ...

Ways to place the footer in the middle of 2 divs?

Hey there! I'm currently experimenting with creating a 3 column layout and running into an issue with the footer placement. I want the footer to go between the two sidebars at the bottom, but my middle column isn't extending all the way down like ...

"Initiate an Ajax call in Full Calendar before an event is displayed on the calendar

I need guidance on how to integrate ajax calls with the Full Calendar documentation. Specifically, I want to make an ajax call to a WordPress database before each event is rendered on the calendar. The response from the call will determine the color of the ...

What is causing the SVG element to malfunction on iOS devices?

I am facing an issue with the <h1> tag in my design. The SVG element within it is not appearing on mobile phones when I write a media query for devices with a minimum width of 400px, even though it works fine on screens with a minimum width of 800px. ...

Basic selection menu layout

I have put together a basic menu for my WordPress site without relying on classes or IDs: <div class="main-menu"> <nav> <ul> <li> <a href="#" class="menu-link">home</a> ...

Tips for making a DIV span the entire width of a page when it is within a column with the Bootstrap class 'col-md-6'

I'm having a little trouble arranging divs next to each other on a page. Specifically, I want to ensure that if there is only one instance of the col-xs-12 col-md-6 div class on the page, it should take up the full width (100%) instead of just 50%. Th ...

Troubleshooting a problem with jQuery and Drupal behavior when the document is ready

Encountering a strange issue with my jQuery code within Drupal 7. I implemented the following snippet : (function ($) { Drupal.behaviors.exampleModule = { attach: myPopUpFunction..... })(jQuery); Interestingly, on Mac browsers, the popup loads af ...

Conflict between jquery and hoverIntent libraries

I've encountered an issue with a website that was functioning properly until we added a new form to a specific page. The form, created by another person, utilizes javascript/jQuery for processing. Since adding this form, it has caused the majority of ...

Utilizing the keydown event in jquery with specific key restrictions

I want to prevent the page from refreshing when the user presses F5 or Ctrl+F5. I have come up with the following code to achieve this, but now whenever I press any key on the page, the function runs and prevents me from filling out textboxes or using ot ...

Submitting an mvc partial view form to send data from the parent view

I am currently working on a MVC 5 App where I have a Parent View that includes a Partial View, allowing users to load images. Upon submitting, the Parent view calls a .Ajax function defined within it, which in turn calls a Method/Controller. My requireme ...

Techniques for transferring images directly into HTML canvas games

I created a thrilling race car game and here is the code snippet: index.html <!DOCTYPE html> <html> <head> <title> Extreme Race Car Game </title> <link rel="stylesheet" type="text/css" href="style.css"> < ...

Tips for organizing divs once another div has been hidden using jquery

I am working towards implementing a live result filter feature. There are three filters available: Good fit, bad fit, and scheduled. When the "Good fit" filter is clicked, it should display panels with the class "good_fit_panel". Let's assume there ar ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...

Adjusting the height property to zero in the absence of an element

I'm currently working on creating a timeline for changeLogs and populating it with data from an AngularJS controller. The issue I'm facing is that the height of the timeline "Line" is set to 6px. This means that even when there is no data in the ...

Issue with alert timing

I am facing an issue with fetching the time_stamp value in jQuery from an input field. When I try to alert the time_stamp, it gives a garbage value. Below is the code snippet that I have attempted: <input type="text" name="time_stamp" id="time_stamp" v ...