Increase the CSS integer by a set value at regular intervals with the help of JavaScript

I am looking to create a simulated loading icon that gives the illusion of loading for some calculations, but in reality, it loads quickly. My plan is to increment the animation every second until it appears "complete". I am using CSS3 animations, with a hover action trigger. You can view the example by hovering over the icon: http://jsfiddle.net/77gkzqo2/

The initial CSS for the "beer" shows an empty glass:

border-top:2px solid #F9F1DC; 
height:20%;

At the end of the animation, it should appear as:

border-top:14px solid #F9F1DC;
height:68%;

I am seeking guidance on how to increment these values using jQuery or JavaScript. The border difference is 12 pixels, and the height percentage difference is 48%.

I envision increasing the border size by 4 pixels and the height percentage by 16% every second, so it takes 3 seconds to reach the final appearance.

I am struggling to implement this in JavaScript. I have some basic pseudo code, but unsure if it's correct or how to proceed further.

function addCSS(){
   // Increment each value
   var height = [The current height CSS]
   var border = [The current border CSS]
   var newHeight = height + 16;
   var newBorder = border + 4;

   [set newHeight as .filler's height]
   [set newBorder as .fillers border size]
}

setInterval('addCSS();', 1000); 

Answer №1

Utilizing jQuery may not be necessary for achieving this effect. Furthermore, consider if triggering the action on :hover is truly what you intend, or if you simply want it to occur once when the page loads. If your goal is to animate with JavaScript every second, it might be more effective to avoid having the CSS already in its final state.

An alternative approach could involve something similar to this using vanilla JS:

var filler = document.getElementById('filler');
var border = 2, height = 20;

var animate = setInterval(function() {
    if (border < 15) {
        border += 0.10;
        filler.style.borderTopWidth = border + 'px';
    }
    if (height < 68) {
        height += 0.40;
        filler.style.height = height + '%';
    }

    if (border>=15 && height>=68)
        clearInterval(animate);
}, 50);

You can achieve better performance without relying on jQuery, especially if you are not well-versed in JavaScript.

While there is room for improvement, this simple fake loader should suffice if a basic solution is all you require.

Just something to consider: why slow down your website unnecessarily if it's currently performing well?

Answer №2

jQuery offers various features for animating elements in unique ways. One such feature is the animate function, which allows you to define the desired end state and transition duration.

If jQueryUI is also being utilized, consider exploring its toggleClass function for adding or removing classes dynamically while maintaining CSS styling.

While it may not be necessary to add libraries solely for animation purposes, if already integrated into your project, leveraging these animation functions can enhance user experience and visual appeal.

Answer №3

If you want to retrieve a css property, follow these steps.

$('mySelector').css('border'); // returns "0px none rgb(0, 0, 0)"

Next, if you wish to change the property:

$('mySelector').css({'height' : 20, 'border' : 5})

For example:

function updateCSS(){
    var currentBorder = $('mySelector').css('border').split('px')[0]; // Extracting only the numeric value.
    var currentHeight = $('mySelector').css('height').split('px')[0];

    $('mySelector').css({'height' : currentHeight + 16, 'border' : currentBorder + 4});
}

setInterval(updateCSS, 1000);

NOTE: Take a look at this demo for further clarification: http://jsfiddle.net/7677a297/4/

Answer №4

Have you considered utilizing CSS animations instead of relying on JavaScript for element animation? Check out this example: http://jsfiddle.net/9c85bkp2/. You can still use JS/jQuery to trigger the animation.

Here's an entertaining twist where the glass graphic is crafted using CSS: http://jsfiddle.net/z1v9oLcq/.

HTML:

<div class="goblet">
    <div class="wine">
       <img src="http://i.imgur.com/xjRq8zP.png" />
        <div class="pourer"></div>
    </div>
</div>

CSS:

body {
    padding:0;
    background-color:#fefefe;
    height:600px;
}

.goblet {
    min-height:32em;
    display:flex;
    align-items: center;
    justify-content: center;
}

.wine {
    position:relative;
}

.pourer {
    position:absolute;
    border-bottom:3px solid #E3A74F; 
    z-index:-1;
    bottom:10px;
    width:100%;
    height:25%;
    background-color:red;
    -webkit-animation: pour-it-out 6s linear infinite;
    animation: pour-it-out 6s linear infinite;
}

@-webkit-keyframes pour-it-out {
    0% {
        border-bottom:3px solid #E3A74F;   
        height: 25%;
    }

    100% {
        border-bottom:18px solid #E3A74F;
        height: 80%;
    }
}

@keyframes pour-it-out {
    0% {
        border-bottom:3px solid #E3A74F;   
        height: 25%;
    }

    100% {
        border-bottom:18px solid #E3A74F;
        height: 80%;
    }
}

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

What is the best way to translate these CSS properties into Mui?

I am currently in the process of transitioning my CSS code to utilize MUI's sx prop and styled() function. However, I have not been able to find any documentation on how to properly convert the following code to MUI syntax. Can someone assist me with ...

What is the most appropriate unit of measurement for creating a responsive design?

I am a beginner in the world of responsive design and I'm currently figuring out how to properly layout plugins on a website when viewed on smartphones. Here's an example: @media (min-width: 568px) { .musicPlayer{ width:600px; height:320 ...

Trouble connecting JavaScript to Node application for proper functionality

After setting up Node/Express/EJS, I am now trying to include js files, but my alert("working"); is not working as expected. Quite ironic, isn't it? The main objective is to load learnJs.js in the browser and trigger the alert so that I can confirm e ...

I am having trouble retrieving a JsonResult from an asp.net mvc controller using $resource in angular

I am new to Angularjs and trying to integrate it with asp.net mvc. I am facing an issue where I am unable to access an asp.net mvc controller to return a JsonResult using $resource in angular. Strangely, when I use $.getJson in JavaScript directly, it work ...

Displaying a pop-up window upon clicking on an item in the list view

After creating a list where clicking an item triggers a popup, issues arose when testing on small mobile screens. Many users found themselves accidentally tapping buttons in the popup while trying to view it. What is the most effective way to temporarily ...

Manipulate text within a text area using jQuery

Good afternoon. How can I use JavaScript to update the text in a textarea input? I currently have some content in my textarea that includes a PublisherImprintName tag, and I want to remove it using jQuery. <PublisherInfo> <PublisherName>A ...

mvc and ajax - failing to access model attributes

I'm encountering an issue where the inputs in my beginform are not being auto-posted successfully. Their values do not reach the model or controller and remain null (breakpoints are never hit). What could possibly be causing this? @model project.Mo ...

The internet explorer browser does not support the keypress event

i have the following code snippet: <input class="any" type="text" id="myId" name="myName" /> this specific input is using a jquery datepicker plugin.. (http://jqueryui.com/datepicker/) Here is my JavaScript for this element: $('#myId'). ...

The useAutocomplete function in Material-UI fails to consider the disabled

Currently, I am working on developing my own Autocomplete component by utilizing the useAutocomplete hook from the mui/base package. Most parts of the implementation are functioning correctly, except for the disabled option. My expectation is that the com ...

Is it possible to access the CSS property from an external CSS file even when inline styles are used?

Is there a way to retrieve the css property from an external source using JavaScript or jQuery even if inline styles are applied to the same element? Here's an example: <div id="my" style='left:100px'>some content</div> <styl ...

Learn how to design a customized loading screen using CSS with Phonegap

Currently working in Android with Phonegap / Cordova, I am faced with the challenge of optimizing page loading time due to numerous DOM objects being created. To address this issue, I am attempting to implement a "Loading..." screen to prevent users from b ...

Receiving Server Emissions in Vue/Vuex with Websockets

In my Vue component, I was using socket.io-client for WebSocket communication. Now that I've added Vuex to the project, I declared a Websocket like this: Vue.use(new VueSocketIO({ debug: true, connection: 'http://192.168.0.38:5000', })) ...

Sorting table data by Table SubHeadings using Jquery

Utilizing jQuery tablesorter in my UI, I encountered a challenge with a table that has 2 rows of headers - one main header and one subheader. My goal is to enable sorting on the subheader. How can I achieve this? Below is an example of my code structure: ...

What is the best way to modify an array of objects within component state?

I am currently working on updating a specific property of an object that is stored in an array. Here's a glimpse of my current state: state = { todos: [ { id: '1', title: 'first item, completed: false }, { ...

incapable of utilizing the $q library and promises

I am trying to make use of the variable StatusASof within the inserthtml function in the following manner. App.controller("SS_Ctrl", function ($scope, $http, $location, $window, $sce, $q) { var ShiftDetails = []; function acquireMAStatusASof(Id) { ...

Which nodejs versions are compatible with async Iterators?

Which iterations of nodejs are compatible with async Iterators? Can it be adapted to function on previous versions of nodejs? usage for await (let content of promises) { // promises => array of promise objects console.log(content); } ...

Animate div visibility with CSS transitions and Javascript

I'm currently working on incorporating an animation into a div that I am toggling between showing and hiding with a button click. While I have the desired animation, I am unsure of how to trigger it using JavaScript when the button is clicked. Can any ...

Hover over two different divs with JQuery

I have a situation where I have two HTML table rows. When I hover over the first row, I want to display the second row. However, once the mouse leaves both rows, the second row should be hidden. Is there a way to achieve this using JQuery? <tr class=" ...

Sending form data from a third-party website to Django

Currently, I am running a Django website that holds user information. My goal is to host forms on external websites, such as a newsletter signup form. I want to be able to extract data from a queryset in the URL and send it back to my Django site. At the m ...

Ways to personalize the onSubmit function within tinacms

Having an issue with my Tina project. I am trying to develop my own submit button in Tinacms project, rather than using the sidebar or top bar provided by tinacms. I want to customize a button for onSubmit functionality. Any suggestions on how to achieve ...