Using Vue.js to fade out one image while fading in another

This piece of code is designed to load a random picture from a collection and replace it with another picture every few seconds, assuming the images are located on the server.

I am attempting to implement smooth fading transitions for the pictures, but I have encountered two issues:

1) I am unable to display 'this.image' when moving it into the setTimeout function.

2) I struggled to get the fadeIn() or fadeOut() functions to work, and I am unsure about the correct syntax to use.

Please refer to the comments within the code. Thank you!

JS:

Vue.component('foo-ad-module', {
    data() {
        return {
            image:  'foo/foo_ad1.jpg',
            timer:  '',
            x:          0
        }
    },
    created: function() {
        this.replaceImage();
        this.timer = setInterval(this.replaceImage, parseInt((Math.random() * 33599)%30000) + 5000)
    },  
    methods: {
        init(){
            this.x = parseInt((Math.random() * 33599)%11) + 1;
              this.image = 'foo/foo_ad' + this.x + '.jpg';
              console.info("this.image = " + this.image);
       },
       replaceImage: function() {
            this.x = parseInt((Math.random() * 33599)%11) + 1;
//#if
           this.image = 'foo/foo_ad' + this.x + '.jpg';     // ...THIS WORKS (when it is outside the setTimeout())
//#else
//          $(???).fadeOut("2000");                                     // ... intending to put a fadeOut() here...
            setTimeout(function () {        
                console.info("this is working...");                                                          
//              this.image = 'foo/foo_ad' + this.x + '.jpg';    // ... THIS DOESN'T WORK (when it is inside the setTimeout())
//              $(???).fadeIn("2000");                                  //  ... intending to put a fadeIn() here...                                         
            }, 2000);
//#endif            

            clearInterval(this.timer)         
        this.timer = setInterval(this.replaceImage, (parseInt((Math.random() * 33599)%30000) + 5000));        
       },
  },
    beforeDestroy() {
      clearInterval(this.timer)
    },  
    mounted(){
        this.init()
    },  
    template: `
                <div class="foo-ad-module " >
               <img :src="image" alt="hi there">
                </div>  `
});

CSS:

.foo-ad-module {
    width:          198px;
    height:         198px;
    border:         1px solid #555;     
    border-radius:  10px;
    margin-bottom:  10px;
}

Answer №1

setTimeout issue with context

In the scenario of setTimeout(function() {});, the context is not correctly assigned, leading to this not referencing your Vue component in the timer callback. If ES6 is supported in your project, you can resolve this problem by utilizing an arrow function:

setTimeout(() => {
  this.image = '...';
}, 2000);

If ES5 is the only option available to you, you must utilize Function#bind to rectify the issue:

setTimeout(function() {
  this.image = '...';
}.bind(this), 2000);

Alternatively, passing a reference to this can also solve the issue:

var self = this;
setTimeout(function() {
  self.image = '...';
}, 2000);

Implementing image fading effect

To achieve a fading effect for the <img> element using Vue's <transition>:

new Vue({
  el: '#demo',
  data() {
    return {
      show: true
    }
  }
})
.fade-enter-active, .fade-leave-active {
  transition: opacity .3s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e080b1b3e4c504b504f48">[email protected]</a>"></script>

<div id="demo">
  <button v-on:click="show = !show">
    Toggle image
  </button>
  <div>
    <transition name="fade">
      <img v-if="show" src="//placekitten.com/100/100" alt="kitten">
    </transition>
  </div>
</div>

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

Using gulp to compile a Vue component without the need for `require` statements

I'm currently exploring the process of constructing a component with Gulp. Right now, I am working on a Vue component that has the following structure: my-component.vue <template> <div class="foo"> </div> </template> < ...

Callback for Variable Change

Is there a way to have a function trigger when a variable changes its value? In the code snippet provided, there is a function called loadImage that fetches the image material. However, if this code is executed, the declaration of mesh and scene.add(mesh) ...

Ways to bypass a promise within a sequence

Currently, I am involved in a nodejs project and I am looking for a way to bypass a promise in a chain. Here is the code snippet I am working with. The initial promise block resolves a value of {success: true}. In the following block, I need to assess th ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...

Variations in the timing of image transitions

Currently, as a GCSE computing student, I am working on being able to modify the interval between different images in my code. Here's what I have so far... <!DOCTYPE html> <html> <body> <h1> Adjusting Traffic Light Changes & ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

ng-if not functioning properly following the activation of the "Save Changes" button

When I click the edit change button, I am updating information and then hiding the form to show the updated details by clicking on the Save Changes button. My API successfully updates the information, but for some reason, ng-if does not seem to work afte ...

What is the best way to display database information on my webpage according to the selected item in the combo box?

Whenever I visit my sample.php page, the only thing that appears is my combo box. However, when I start selecting a value from the combo box, that's when the data from my database, which is fetched from getyear.php, is displayed. What I want to achie ...

JS Code from a JS Fiddle failing to run in a web browser examination

I have been experimenting with a fantastic Expand/Collapse JavaScript function that I came across on JS Fiddle, but unfortunately, it's not working as expected when testing it in a browser. Can anyone provide some guidance on what might be causing the ...

When the jquery is still running, HTML initiates the loading of a new page

When I click on an anchor HTML tag with a link, I want to change the value of a variable in jQuery. However, even though the tag loads a new page, the variable's value remains unchanged. After doing some research online, I discovered that this issue ...

Issues Persist with Making Ajax Calls to Webservice

I've been attempting to make a simple web API call from within an HTML page using ajax when a button is clicked. However, the call consistently fails. Oddly, the issue seems to only arise with the ajax call triggered by the button click, as the loadin ...

Organize object keys based on the size of the arrays they contain in JavaScript

I'm working on a project where I need to organize a list of products by manufacturer, displaying them from the one with the most products to the least. I'm looking for an algorithm that will help me sort the object keys accordingly. Below is a s ...

I seem to be having issues with the way the lighting is functioning in three.js; it is not acting

There's this fiddle I'm working on, you can check it out here. It contains the html/js code for a terrain generated by PHP. The problem I'm facing is that the shadow and other renderings are not displaying as expected. Here is my current l ...

What is the best way to modify the glyphicon within the anchor tag of my AJAX render property?

Consider the use of Ajax: "target 0" with a render option for an anchor tag. Initially, I am utilizing the class "glyphicon glyphicon-chevron-right". Now, I wish to change it to "glyphicon glyphicon-chevron-down" when clicked. $(document).ready(funct ...

Performing a multitude of if statements simultaneously consistently results in an undefined outcome after the sixth iteration

Oops! I can't believe I forgot my original question! Every time I run the sixth if statement in my code, I encounter a typeError Undefined. Interestingly, when I switch the positions of the fifth and sixth statements, the if(!data.body.main) condition ...

Creating an array with conditional elements in React involves utilizing the map method along with a conditional

My array, named tableFilterFields, looks something like this: const tableFilterFields = [ { label: "Start Date", name: "StartDate", type: FilterControls.DatePicker, defaultValue: new Date(new Date().setDate( ...

Just diving into JavaScript, what makes jQuery so powerful?

As a newcomer to javascript (although functional programming is no problem for me), I find myself questioning some of the design choices made by jQuery. Is it too late to make changes now, or are they simply too ingrained in the framework? For example, the ...

Storing dataset characteristics in a JSON file utilizing Vue.js form response

I am currently working on creating a JSON file to store all the answers obtained from a Form. Some of the input fields have an additional dataset attribute (data-tag). When saving the Form, I aim to extract these 'tags' and include them in the JS ...

Step-by-step guide on how to effectively send a NodeJS request and stream it into a separate response

Currently, I am in the process of developing an API to interact with a specific map service that requires the use of an API key. It is crucial for me to keep this API key private. To achieve this, I plan to make internal calls within my server's own A ...

Identify the distinct item by its name within the array

I need assistance in filtering out unique place names from the list Array's places Array. Below is an example of the array data=> "list":[ { "id":1, "uID": 1 "places":[ { ...