Layering transitions

UPDATE: Initially labeled as Mootools' child index refresh

Understanding the inner workings of Mootools can be a bit challenging, but it appears that when an element is removed from the DOM and then reinserted at the bottom of its container, the order of elements retrieved using methods like getNext() or getChildren()[0] may not align with the expected visual order in the HTML.

Below is the code where I am encountering an issue. Despite my efforts, I'm uncertain if the explanation above accurately identifies the root cause.

function slideNext() {
    window.clearTimeout(sliderTimeout);
    var slider = $('slider');
    slider.set('tween', {duration: 500, onComplete: function(){
        var slide = slider.getFirst('.block').clone();
        slider.grab(slide, 'bottom');
        slider.getFirst('.block').destroy();
        slider.erase('style');
        sliderTimeout = window.setTimeout(function(){slideNext();}, 5000);
    }});
    slider.tween('margin-left', 0 - slider.getSize().x);
}

UPDATE: Adding an alert(slide.get('html')); within the onComplete function provides some clarity. Interestingly, with each execution of the function, the number of alert dialogs increment unexpectedly, despite being intended to fire only once. This behavior suggests that recurrently setting slider.set('tween', {blabla}) leads to cumulative tweens, prompting me to suspect a potential issue with child indexing, which is ultimately disproven. The revised version below resolves the issue smoothly:

function slideNext() {
    window.clearTimeout(sliderTimeout);
    var slider = $('slider');
    var myFx = new Fx.Tween('slider', {
        duration: 500, 
        property: 'margin-left',
        onComplete: function(){
            var slide = slider.getFirst('.block').clone();
            slider.grab(slide, 'bottom');
            slider.getFirst('.block').destroy();
            slider.erase('style');
            sliderTimeout = window.setTimeout(function(){slideNext();}, 5000);
        }
    });
    myFx.start(0, 0 - slider.getSize().x);
}

Could someone shed light on this behavior?

Answer №1

essentially, the original code is as follows:

slider.set('tween', {duration: 500, onComplete: function(){
    var slide = slider.getFirst('.block').clone();
    slider.grab(slide, 'bottom');
    slider.getFirst('.block').destroy();
    slider.erase('style'); 
    sliderTimeout = window.setTimeout(function(){slideNext();}, 5000);
}});

when you call the setter on the tween instance, it recognizes the event prefixed by on-(Complete), extracts it, and executes this.addEvent('complete', cb);. this does not replace the previous event, as MooTools has an event API that supports multiple callbacks, not just one static callback.

one solution could be to detach the event before calling the next one, but it seems unnecessary since the event remains the same. a more logical approach would be to set the tween instance only once, given that the element doesn't change. I'm not entirely sure of its purpose, but here's an example: http://jsfiddle.net/dimitar/3qWX7/

(function(){
    // cache the slider element, store the tween instance.
    var slider = document.id('slider').set('tween', {
        duration: 500,
        link: 'cancel',
        onComplete: function(){
            var block = this.element.getFirst('.block');
            // this.element === slider
            this.element.adopt(block.clone());
            block.destroy();
            this.element.erase('style'); // why though... 
            // console.log(this.element);
            this.timer = slideNext.delay(5000, this);
        }
    });

    // retrieve the instance using:
    slider.get('tween'); // Fx.Tween instance

    function slideNext(){
        // this == Fx.Tween instance. 
        window.clearTimeout(this.timer);
        this.element.tween('margin-left', [0, this.element.getSize().x]);
    }

    slider.tween('margin-left', 40);
}());

however, this method may encounter issues with other tweens - the event is not directly linked to the property being tweened. if needed, you would have to use fx.morph and adjust events accordingly.

tl;dr;: always re-use fx instances, references to dom, etc. should be cached for optimal performance.

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

Struggling to retrieve a particular field from Mongodb with the .find() method (Beginner)

I am a novice. Here is my code. Essentially, I am storing my JWT in MongoDB and it is being stored properly. However, when I try to fetch that token to verify it, I am unable to retrieve it. The console.log(find_refreshtoken) is displaying unexpected data ...

Make a request using jQuery AJAX to retrieve data from a specific column

I'm trying to extract column data from my database using a jQuery AJAX request, but I keep running into issues. Can someone point out what I might be doing wrong? Basically, when I click a button, I want to retrieve an array of values. javascript : ...

Tips for retrieving the slug value in getStaticProps for invoking the API with the slug as a parameter

Content on the Page: import { useRouter } from "next/router"; export default function Daily({ data }) { let router = useRouter() const { slug } = router.query; return slug; } And display on the page 60d6180ea9284106a4fd8441 ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

Navigating through child components in React

As a newcomer to react application development, I recently embarked on my first project. My goal was to showcase 5 buttons within a table. Initially, I took the straightforward approach of hardcoding them in Table.js Table.js <Button hidden={ ...

An issue has occurred: Angular2 is reporting that Observable_1.Observable.defer is not recognized as a

Recently, I made the transition of my Angular app from version 4 to 6. Here is a peek at my package details: Package.json file: { "version": "0.10.50", "license": "MIT", "angular-cli": {}, ... Upon running npm run start, an error popped up in th ...

Potential problems with variable assignment and conditional statements in Internet Explorer can lead to unexpected

Here is a simple code snippet: var myvar = $('.chosen').text(); if (myvar == "bar") { //perform some actions...} This works perfectly in Safari, but not in Chrome. Any idea what could be causing this issue? When I run alert($('.s ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

How can we dynamically reference past elements in an array without using indices like "i-1", "i-2", and so on?

function play_tune(melody) { let played_notes = []; let durations = []; let positions = []; let wait_time = 0; let time_passed = 0; console.log("Melody initiation.") for (let key in melody) { played_notes.push(melody[key].note); dur ...

The environmental variable remains undefined even after it has been established

I've been experimenting with setting my environment variable in the package.json file so that I can access it in my server.js file. Despite trying NODE_ENV=development, set NODE_ENV=development, cross-env NODE_ENV=development, and export NODE_ENV=deve ...

Unable to create a random number using JavaScript

Looking for a bit of help with this code snippet: <!DOCTYPE html> <html> <head> <title>Test Your Luck Here!</title> <script type="text/javascript"> function myFunction() { var x = Math.floor((Math.random() * 6) +1); doc ...

"How to Develop an Eraser Tool Using EaselJs - Exploring Further Possibilities

Currently, I am working on creating a Bitmap eraser on easelJS. I feel like I've made significant progress towards achieving this goal, but I'm still a bit unsure of the next steps... Here is a demo of my progress so far: http://jsfiddle.net/bor ...

The HiddenField is returning empty when accessed in the code behind section

In my gridview, the information is entered through textboxes and saved to the grid upon clicking a save button. One of these textboxes triggers a menu, from which the user selects a creditor whose ID is then saved in a HiddenField. <td class="tblAddDet ...

What is the best method for performing a color-specific hit test on a specific image within a webpage?

I want a way to detect when my mouse hovers over a specific image and changes color upon hovering over it. Is there a way to achieve this and what steps should I follow? ...

Could not successfully enroll a ServiceWorker in Next.js

After creating a sample Next.js project using the command: npx create-next-app, I then installed next-pwa. Following that, I configured next.config, created manifest.json, and _document.js in the project directory. This is my next.config.js: const withPWA ...

Is it possible to add or remove a class at the top of a div

Is there a way to create a fading effect for a class based on when a specific div enters the window? I am looking to implement this functionality, how can I achieve this? $(window).scroll(function() { var registerTop = $('.register').offset ...

The success event in jQuery's $.ajax function is being triggered last

When running the following Javascript code, I noticed that the results are not being returned in the expected order. function getCurrentItems(id){ alert("2"); $.ajax({ url: "somePHPurlthatspitsoutajsonencodedArray.php", type: "POST ...

Insert fixed text before or after the input value without altering the value itself

Is it possible to prepend or append additional text to an input value? I am looking to customize the display of a value without altering the actual value itself. For instance, if the value is 1000, I want it to still return 1000 when accessed. <input ...

I am having trouble getting the hoverOffset feature to work with doughnut charts in vue-charts.js

It appears that no matter what I try, the hoverOffset property is not working on my doughnut charts. Here's the component code: <script> import { Doughnut } from 'vue-chartjs' export default { extends: Doughnut, props: { ch ...

What is the reason Angular is unable to locate a controller for a directive in an external file?

As a newcomer to Angular, I'm struggling to comprehend John Papa's recommendations. His guidelines suggest placing controller logic inside directives, but this approach doesn't seem intuitive to me. Despite my efforts to implement it myself, ...