Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffective as it will not resize the background image to fit the screen but rather display it 'as is'. A better understanding can be gained from viewing it here (note that #slides would have both height and width set to 100%, as well as .slide>img). I have exhausted my ideas on how to resolve this issue, any assistance would be greatly appreciated. I would prefer not to utilize jQuery, but I am open to it if necessary.

Thank you in advance.

This is what my script looks like so far:

function animateBlocks(x,y,speed) {
var width = document.getElementById('slides').offsetWidth;
var height = document.getElementById('slides').offsetHeight;
var newWidth = width/x;
var newHeight = height/y;

for (var i = 0; i<(x*y); i++) {
    var newDiv = document.createElement("div");

    document.getElementsByClassName('active-slide')[0].appendChild(newDiv);
    newDiv.className = "slide-block";
    newDiv.style.width = newWidth + 'px';
    newDiv.style.height = newHeight + 'px';
    newDiv.style.backgroundImage = 'url("' + document.getElementsByClassName('active-slide')[0].firstElementChild.src + '")';
    newDiv.style.backgroundPosition = ('-' + newDiv.offsetLeft + 'px ' + '-' + newDiv.offsetTop + 'px');

    if (i == x*y-1) {
        document.getElementsByClassName('active-slide')[0].firstElementChild.style.display = 'none';
    }
}

}

Answer №1

After reviewing the feedback from the comments, it appears that the issue arises when there is a float value present in the window's width. To address this, you can utilize `document.documentElement.getBoundingClientRect();` to obtain an accurate size and then round down the value to prevent blocks from overflowing to the next row. For a demonstration, you can visit this jsfiddle

function animateBlocks(x,y,speed) {
    var img = document.querySelector('#slides img');
    var viewPortSize = document.documentElement.getBoundingClientRect();
    // Rounding down to avoid floating point issues.
    var windowWidth = Math.floor(viewPortSize.width);
    var windowHeight = window.innerHeight;
var newWidth = windowWidth / x;
var newHeight = windowHeight / y;
    
    var newDiv;
    var domFrag = document.createDocumentFragment();
    var i, j;
    for (i = 0; i < y; i +=1) {
        for (j = 0; j < x; j += 1) {
            newDiv = document.createElement("div");
            domFrag.appendChild(newDiv);
            newDiv.className = "slide-block";
            newDiv.style.width = newWidth + 'px';
            newDiv.style.height = newHeight + 'px';
            newDiv.style.backgroundImage = 'url("' + document.getElementsByClassName('active-slide')[0].firstElementChild.src + '")';
            newDiv.style.backgroundSize = windowWidth + 'px ' + windowHeight + 'px';

            newDiv.style.backgroundPosition = ('-' + newWidth*j + 'px ' + '-' + newHeight*i + 'px');
        }
    }
    
    for (var i = 0; i<(x*y); i++) {

}
    document.getElementsByClassName('active-slide')[0].appendChild(domFrag);
    document.getElementsByClassName('active-slide')[0].firstElementChild.style.display = 'none';
}
body {
    width: 100%;
    height: 100%;
    margin: 0;
    overflow: hidden;  /* hides the scroll bar */
}

#slides {
position: relative;
height: 100px;
        margin: 0px;
        padding: 0px;
}

.slide {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
display: none;
}

.slide>img {
position: absolute;
left: 0;
top: 0;
height: 100px;
}

.active-slide {
display: block;
}

.slide-block {
float: left;
}
<button onclick="animateBlocks(5,5,0)">Click here to see how it looks</button>
<ul id="slides">
<li class="slide active-slide">
<img src="http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg">
</li>
</ul>
   <br><br><br><br><br><br>
    <p>How it should look</p>
    <img style="height: 100px;" src="http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg">

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

Run the command "node index.js" to simultaneously start and stop the server

After installing WSL2 and the Ubuntu 22.04 distribution on Windows 11, I set up my environment, installed nvm, Node version 16.17.1, and then ran npm init in my folder. Following that, I installed Express and created an index.js file with a simple structur ...

Is the Order of a JSON Array Dependable?

When working with JSON, it's clear that relying on the ordering of key-value pairs may not be reliable. For instance, a JSON parser could interpret { "someKey" : "someValue", "anotherKey" : "anotherValue", "evenAnotherKey" : "evenAnotherV ...

Obtaining the Div ID After Clicking on a Link

I'm attempting to fade out a box once the X in that box is clicked. I haven't been able to make it work even after searching on Google. I managed to get it working when clicking the div itself using $(this), but my goal is for it to work when the ...

Steps for triggering the material-ui menu to appear on hover of a button

I attempted to implement the following code without success. I was able to achieve it using plain CSS, but I need to utilize the makeStyles function provided by material-ui. My goal is to display a drop-down list of items when a user hovers over the butto ...

Flexbox CSS Card Layout Behavior

Looking to achieve a specific design effect without relying on Semantic UI? Check out the codepen link here: https://codepen.io/anon/pen/YxBOax <div class="ui container"> <div class="ui four cards stackable"> <div class="teal card"> ...

"AngularJS offers a unique way to include alternative text in placeholders and titles using

I need to implement an input field (<input..>) with a placeholder and title for tooltip that functions in the following way: There is a variable called "myString" which can either be undefined/empty or contain a string. When empty, a default string ...

Struggling to interpret JSON data from an AJAX call using jQuery in a Python/Flask application

Currently, I am attempting to analyze a POST request sent via AJAX using jQuery in a python script. The structure of the request is as follows: request.js function get_form_data($form){ var unindexed_array = $form.serializeArray(); var indexed_ar ...

Click the submit button to display a div element without having to refresh the page

Is it possible to display a spinner for a couple of seconds before the page reloads upon submitting a form? <form class="ready" action="https://link.com" method="post"> <input name="test" type="submit" class="click" value="order"/> </form&g ...

Prevent unauthorized entry to css and javascript files

Is there a way to prevent direct access to a file? I want the file to be used on my website, but I want to block it from being accessed directly. For example, if you try to open this link: https://example.com/style.css, you will see an error message. Howev ...

Unlocking Bootstrap variables in Vue development (using Vanilla Bootstrap)

What is the best way to customize or theme bootstrap? I have heard that using sass to override bootstrap variables is recommended, but how can I integrate this into the Vue webpack workflow? I tried searching online and found suggestions to edit the vue.c ...

Incorporate a Variety of Elements onto Your Webpage

I have developed a custom tooltip plugin using JQuery, and I am implementing it on multiple A tags. Each A tag should have a unique tooltip associated with it, so I have the following code: var $tooltip = $("<div>").attr("id", tooltip.id).attr("cla ...

Having trouble with protractor's sendKeys function when trying to interact with md-contact-chips

Does anyone know how to set a value using sendKeys in Protractor for md-contact-chips? I attempted to use element(by.model('skills')).sendKeys('Java'); but it doesn't seem to be working. Any suggestions on how to approach this in ...

The Firebase cloud function will only activate when I manually input data into the Firestore database via the console

I'm having trouble getting my function to trigger when I programmatically add data to Firestore. It only seems to work when I manually add data through the console. Below is the code for my function: exports.updateFirestoreStatistics = functions.fir ...

Warning from Google Chrome: Ensure password forms include optional hidden username fields for improved accessibility

Upon visiting the "reset password" route of my single-page application and checking the Chrome browser console, I am presented with a warning message: [DOM] Password forms should contain (optionally hidden) username fields for accessibility: (More info: g ...

Showcasing solely the latest entry in the database utilizing nodeJS

I am having an issue with my code where it is only displaying the last record from the database. How can I modify it to display all the records from the database using nodeJS? Any assistance would be greatly appreciated. Thank you. var express = require ...

Retrieving information from Firebase after updating it

My goal is to automatically navigate to a specific ID after adding an item to my realtime database. Despite following the documentation's proposed solution, I am encountering issues with its implementation. Following the use of the push().set() meth ...

The title tag's ng-bind should be placed outside of the element

When using ng-bind for the title tag inside the header, it seems to produce unexpected behavior. Here is an example of the code: <title page-title ng-bind="page_title"></title> and this is the resulting output: My Page Sucks <titl ...

Regular expressions are compatible with JavaScript, but unfortunately, they are not supported

After successfully implementing this regex in my JavaScript for webpage validation, I attempted to incorporate it into my PHP script as a backup. However, every string I passed through the regex failed, even correct names. In an effort to resolve the issu ...

Aligning images of varying sizes

I have implemented a PHP script that automatically resizes images proportionally to fit within a given height and width. For example, if the original picture is 200x100px and the target box is 180x180px, the resized image will be 180x90px. Although this s ...

Saving the selections from two drop-down menus into a single variable

I have a requirement to store the user selected values from two dropdown menus. These dropdowns are created using the selectize library in HTML: <div style="max-width: 200px"> <select id="dropdown-1" ...