The value of a variable remains constant even when it is assigned within a function

I developed a dynamic image slideshow using HTML and JS specifically for the Lively Wallpaper app.

This app offers various customization options, which are stored in the LivelyProperties.json file along with input types such as sliders and text boxes.

To access these properties, one needs to define a function called

function livelyPropertyListener(name, val){}
within the HTML code.

Inside the .json file, there is a slider that can be adjusted through the app's menu. When the slider value changes, it updates the number displayed in a <div> using .innerHTML, however, the variable transitionDuration retains its old value.

The animation function anime used in the code is from the anime.js library.

Upon opening the .html file in Firefox, no errors are reported, indicating that the internal JavaScript functions properly.

        var textEl = document.querySelector(".text");
        var transitionDuration = 3000;
        var imageInterval = 5000;

        function livelyPropertyListener(name, val) //I assume this function is recognized when the .html file is parsed in the app
        {
            if(name =="transitionDuration")
            {
              transitionDuration = val; //transitionDuration stays 3000 (the value in the beginning of the code)
              textEl.innerHTML = val; //this works and the text updates as the slider is moved (due to app limitations file needs to be reloaded for it to updated, but that's fine)
            }
        }

        var ScaleEasingFunc = 'easeInQuad';

        anime({
          targets: '.transition',
          opacity:0,
          direction: 'alternate',
          loop: true,
          easing: 'easeInOutCubic',
          delay: imageInterval/2,
          endDelay: imageInterval/2,
          duration: transitionDuration,
          loopBegin: function(anim) {
            changeImage();
          },
        });

        anime({
            targets: '.scale',
            scale:1.1,
            translateX: screen.width*-1/100,
            translateY: screen.width*1/100,
            direction: 'alternate',
            loop: true,
            easing: ScaleEasingFunc,
            duration: imageInterval + 2*transitionDuration,
        });
</script>

Answer №1

Consider the sequence of events:

  1. var transitionDuration = 3000; sets a value for transitionDuration
  2. function livelyPropertyListener creates a new function
  3. anime({...}) retrieves the current value of transitionDuration, assigns it to an object property, and then passes the object to the anime function
  4. When you invoke livelyPropertyListener, it updates the value of transitionDuration

It's important to note that step 4 does not alter the past to reflect that transitionDuration had already been updated when it was read in step 3.

If you wish to modify the behavior of the anime function after initialization, it should return a value that offers an API allowing you to adjust the duration.

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

Receiving an item in place of a true/false indicator

I wrote an asynchronous function that validates the permission status on a device. Here is the function: checkPermission = async () => { const allowed = await requestNotifications(['alert', 'sound']).then((res) => { if ...

PHP tutorial: Accessing a specific key within a JSON object

There is a JSON object that I have been working with: $json = '{ "droplet":{ "id":3286068, "name":"some.domain.com", "memory":512, "vcpus":1, "disk":20, "locked":false, "status":"active", "kernel":{ ...

I am looking to upload an image to the database using ajax or any alternative method

I need assistance in uploading an image to a Spring Boot backend via AJAX or any other method. Below is the img tag and form I have implemented, along with an AJAX request to send form data. How can I include the image in this process? AJAX request (exclu ...

The dropdown menu in the navigation bar is overlapping with the datatable, creating a transparency effect

Working on a website layout that features a navbar at the top and a datatable below. However, when hovering over the navbar to reveal subitems, I notice a transparency issue where the navbar overlaps with the datatable. Below is a simplified version of my ...

jQuery floating sidebar that dynamically adjusts position based on content overflow

I've come across an interesting scenario with a fiddle that I'm working on: http://jsfiddle.net/yFjtt/1/ The main concept is to allow users to scroll past the header and have the sidebar 'stick' in place as they continue scrolling down ...

Struggling with understanding how to parse JSON in VB.net

Looking for some assistance. I'm grappling with parsing the JSON output provided by the cloudstack API in vb.net and feeling a bit stuck. The JSON response from the cloudstack looks like this: { "listcapacityresponse": { "count": 6, ...

Guide on invoking the server-side method in Office 365 using JavaScript files

Exploring the capabilities of office 365 API apps and looking for documentation on how to access specific row(s) and cell(s) values / select a particular sheet programmatically in a .js file. Currently, I am utilizing the following code within a function: ...

"Extracting information from the axios header and passing it to a Vue component: A step-by-step

I am working with an axios apiClient and trying to retrieve the email stored in localStorage to use in the header of my component. I attempted to access the email by using response.headers['email'] and storing it in a variable called email, but ...

Reposition the selection column to the right side within the UI-Grid

I am currently working with ui-grid and I need help relocating the selection column to the right side. Appreciate any assistance. Thank you! ...

Using JavaScript, aim for a specific element by its anchor headline

I'm looking to make some changes to my navigation menu, specifically hiding the home menu item unless the mobile navigation menu is toggled. Is there a way for me to target the "home" anchor title and apply the active class to it when toggled, similar ...

Is there a way to efficiently fetch localStorage data upon launching a React application and seamlessly store it in Redux using the useEffect hook without experiencing any data loss issues?

Should I avoid mixing React hooks and mapStateToProps in my application and instead use Redux hooks like useSelector? In my React app, I have an array of 'friend' data stored in Redux. Using useEffect in one of my components, I am saving this da ...

"Exploring the depths of nested JSON objects with Retrofit in Android development

I'm having trouble parsing dynamic JSON data in Retrofit. Here is a sample of the JSON structure with keys that are generated dynamically. What kind of POJO definition should I use for this type of JSON data? { "Fri Mar 23 2018 17:35:36 GMT+0 ...

Struggling to create a BMI Calculator using JS, the result is consistently displaying as 'NaN'

Having trouble creating a BMI Calculator using JavaScript. The issue I'm facing is that the calculation always returns 'NaN'. I've tried using parseInt(), parseFloat(), and Number() but couldn't solve the problem. It seems that the ...

The EJS view fails to render when called using the fetch API

Within my client-side JavaScript, I have implemented the following function which is executed upon an onclick event: function submitForm(event) { const data = { name, image_url }; console.log(data); fetch('/', { method: &apo ...

SCORM: moving between SCOs by clicking a button in the presentation

Currently, I am developing a website that allows users to create presentations. One of the website's features is the ability to export presentations in SCORM format (either 1.2 or 2004). This is my first time working with SCORM and I am currently impl ...

Transform JavaScript variables into CSS variables

Similar Post: Avoiding repeated constants in CSS I am currently working on a javascript file that aims to adjust my site's resolution based on the width and height of the viewport. While I have successfully retrieved these values using JavaScript ...

"The PATCH method in HttpWebRequest doesn't play well with JSON, resulting in a

Attempting to send data to a REST API poses some challenges. The API documentation specifies using the PATCH method and providing the data in JSON format. Additionally, utilizing oAuth 2.0 for authentication is required before making the call by obtaining ...

When a child component sends props to the parent's useState in React, it may result in the return value being undefined

Is there a way to avoid getting 'undefined' when trying to pass props from a child component to the parent component's useState value? Child component const FilterSelect = props => { const [filterUser, setFilterUser] = useState('a ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

Utilizing Jasper Reports: Sending JSON Input/Output Stream to Included Subreport

I currently have a report that includes a subreport which uses a JSON source file as its data source. In this setup, I pass the path to the JSON file using the subReportParameter net.sf.jasperreports.json.source. Now, if I switch to using a JSON IO stream ...