Tips for enhancing the transition effect of animated gifs on a webpage using JavaScript

In my code, I have an interval set to run every seven seconds. Within this interval, there are two gifs that each last for seven seconds. My goal is to display one of the gifs in a div (referred to as "face") based on certain conditions - for example, if the Time is a multiple of 14. However, there seems to be an issue where there's always a black screen between the transitions. I am looking for a solution that allows for a seamless transition without the black frame interrupting.

    const face = document.getElementById('face');
    var  one = "<img src='1.gif'/>";
    var  two = "<img src='2.gif'/>";
    Time = 0;
    function myTimer() {
            Time = Time + 1;
            if (Time%14 ===0){
              console.log("gif one");
              face.innerHTML = one;
            }else{
              console.log("gif two");
              face.innerHTML = two;
            }
    }
    var myVar = setInterval(myTimer, 7000);
<div class="content">
    <div id="face">  </div>
  </div>

Answer №1

An effective strategy could be to embed the <img src='1.gif'/> and

"<img src='2.gif'/>"
in the HTML code, then use either display:none or opacity:0 to conceal it, toggling back to opacity:1 or display:revert every 7 seconds.

Allowing the browser ample time to load the desired gif is crucial for a seamless transition. Utilizing opacity: 0 and display:none ensures that the image loads during page loading, resulting in a smooth transition.

A potential issue arises when specifying the duration of each gif to last for 7 seconds, yet setting conditions for the first gif to appear only at multiples of 14, limiting its display to every 98 seconds. To rectify this, consider changing Time%14 === 0 to Time%2 === 0.

const face = document.getElementById('face');

    var one = document.getElementById('img1')
    var two = document.getElementById('img2')
    Time = 0;
    function myTimer() {
            Time = Time + 1;
            if (Time % 14 === 0){
             one.style.opacity = 1
             two.style.opacity = 0;
             console.log('gif1')
            }else{
               one.style.opacity = 0;
              two.style.opacity = 1;
               console.log('gif2')
            }
    }
    var myVar = setInterval(myTimer, 7000);
img{
opacity: 0;
position: absolute;
left: 20px;
top: 20px;
}
<div class="content">
    <div id="face"><img id ='img1' src='1.gif'/>
    <img id='img2' src='2.gif'/></div>
  </div>

Answer №2

Thanks to James for suggesting the use of style.opacity, which helped me resolve the issue I was facing. However, it's important to note that simply adjusting opacity or display properties wouldn't have easily fixed the problem. With James' guidance, I was able to finalize the code as shown below:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>Talk</title>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="content">
    <div id="face">    
        <img id ='img1' src='1.gif'/>

        <img id= 'img2' src='2.gif'/>
    </div>
    

  </div>
  <script type="text/javascript">
    const face = document.getElementById('face');
    var  one = document.getElementById('img1')
    var  two = document.getElementById('img2')
    Time = 0;
    function myTimer() {
            Time = Time + 1;
            if (Time%2 ===0){

                one.style.opacity = 1;
                two.style.opacity = 1;
                
                function myTimer2(){
                    two.style.opacity = 0;

                }
                var myVar2 = setTimeout(myTimer2, 500)                
            }else{               
                one.style.opacity = 1;
                two.style.opacity = 1;
                
                function myTimer3(){
                    one.style.opacity = 0;
                }
                var myVar3 = setTimeout(myTimer3, 500)   
            }
    }
    var myVar = setInterval(myTimer, 5000);


  </script>



 
</body>
</html>

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

Do not reload the page after a successful ajax request

I'm using an Ajax section to submit data in Laravel. I want the page to not reload if the submission is successful, but to reload if there's an error. Currently, when there is an error, the page reloads correctly. However, I'm facing an issu ...

Analyze arrays within object properties to identify discrepancies between them

Stuck on a Programming Challenge I am currently working on a project that involves using a JSON file along with express/nodejs, and I have hit a roadblock with a specific task that requires the following steps: Using a post route, the aim is to identify ...

Tips for transferring parameters between AJAX requests

Struggling to pass parameters between two different ajax calls, I've noticed that the params only exist within the ajax scope and not outside of it. Is there another way to achieve this without calling from one ajax success section to another ajax? He ...

Tips on storing Jquery click event in local storage to temporarily conceal CSS styling

I need some assistance with Javascript, as I am not very proficient in it. I have created a CSS code that displays an announcement when the webpage loads, along with a close button to hide the entire CSS and its contents using JQuery animate. My goal is t ...

Ways to interpret and contrast the information within files (verifying if the lengths of the strings are identical)

I have a web tool where users can upload text and code files, which are then saved in a local directory. I'm trying to create a function that reads these files, compares their lengths, and generates a report indicating whether they are equal or not. B ...

Exploring the intricacies of node.js module 'config' and its configuration files default.json, production.json, and uncovering issues with a specific "Configuration property"

https://github.com/node-config/node-config Here is a quote from GitHub: To install in your app directory, follow these steps: $ npm install config $ mkdir config $ vi config/default.json" The overview explains the installation process and mention ...

What causes the border to trigger the appearance of a scrollbar due to an overflow?

The first image display a scrollbar, while the second one does not. It all comes down to the .tabulator CSS class and specifically the border property. How come only a 1px border impacts the scroll feature instead of affecting the entire content? https: ...

Combining round brackets and square brackets when initializing an array

In the snippet below, values are assigned with a mix of parentheses and square brackets without any errors. However, most other combinations (such as parentheses inside square brackets) do not work at all. var myItems = []; myItems[5] = ("A1", "B1", ["C1" ...

A guide on utilizing a dropdown menu in PHP to showcase various MySQL tables

I am looking for a solution to display different tables (table 1 to 5) from my MySQL database when selected from a drop-down list. However, when I attempted to execute the code below, I did not receive any response and no data was loaded from the SQL datab ...

Bug with the animation of height in Jquery

Unfortunately, I can't share my entire source code here because it's quite lengthy. However, maybe someone can provide some insight into a common issue that may be happening elsewhere. The problem I'm facing is with a DIV element that has r ...

Creating an infinite scroll with a gradient background: a step-by-step guide

I am currently working on a project to develop an infinite scrolling webpage with a dynamic gradient background that changes based on the user's scroll position. While researching, I came across some code for infinite scrolling using time and date. I ...

Capturing Screenshots with Ionic Framework

I am currently working on an Ionic application that utilizes geolocation via the Google API. However, I am facing a challenge with implementing a feature where a button in the upper right corner should take a screenshot and trigger a popover with options t ...

Unwrapping React: Mastering the Art of Prop Extraction and Sharing

Imagine I have 2 input elements below, both with the same props except for the className <ReactCardFlip> <input type="text" maxLength={1} className={inputStyles.input} defaultValue={value} ...

How to remove the horizontal scrollbar from material-ui's Drawer element

My drawer is displaying a horizontal scroll, despite my efforts to prevent it. I've tried adjusting the max-width and width settings in Menu and MenuItems, as well as using box-sizing: border-box. I also attempted setting overflow: hidden on the Drawe ...

The issue with the jQuery class change not being triggered in Internet Explorer seems to be isolated, as Chrome and

This little jQuery script I have is supposed to show a fixed navigation menu once the page has been scrolled below 200px, and then change the class on each menu list item to "current" when that section reaches the top of the viewport. The issue is that th ...

Instructions for making dropdown menus that dynamically reduce their options as you make selections:

I have an HTML form structured like this: Within the dropdowns, there is a uniform list of choices: Option 1, Option 2, Option 3. Users must select a value for each key, which currently functions correctly: Yet, I am seeking to enhance this functionality ...

Update the canvas box's color when you interact with it by clicking inside

I'm in the process of developing a reservation system and I'm looking to implement a feature where the color of a Canvas changes when clicked. The goal is for the color to change back to its original state when clicked again. Snippet from my res ...

Rearrange and place items at the dropped location

I am looking to create a drag-and-drop feature for moving items from a list of products to an empty container. Upon completion, I need to save the location and the selected items in a database so that I can recall this layout later. However, I have encoun ...

Avoiding GulpJs freezing with effective error handling techniques

I am currently in the process of converting my sass files to css and encountering some issues. Specifically, I am struggling with handling errors during the sass conversion process. Whenever there is an error, it causes gulp to hang, requiring me to rest ...

The div is empty when trying to display Google Maps

When I set the height of my Google map div in pixels, it displays correctly. However, when I try to set it as a percentage, specifically 100%, the map does not show up. I have tried setting the height of all parent divs as well, based on suggestions from S ...