0

Coming from C#, I have some problems using a variable from another function:

// Define colors
albumart.addEventListener('load', function () {
    var vibrant = new Vibrant(albumart);
    var swatches = vibrant.swatches()
    for (var swatch in swatches)
        if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
            var darkvibrant = swatches.DarkVibrant;
        }
})

// Toggle styles
function mainUpdate(type) {
    if (type == "music") {
        isplaying ? albumart.src = "/var/mobile/Documents/Artwork.jpg?" + milli : albumart.src = "images/No-album-art.png";
        isplaying ? icons.style.color = darkvibrant : icons.style.color = "#202727";
    }
}

I am trying to use darkvibrant in the second function, I tried this:

var darkvibrant = {};

darkvibrant.color = swatches.DarkVibrant;

isplaying ? icons.style.color = darkvibrant : icons.style.color = "#202727";

I would appreciate any help.

Daniell
  • 59
  • 6

1 Answers1

0

You need to make the variable global. So declare the darkvibrant variable outside the first function to make it global and then initialize in the first function.

var darkvibrant; // make it global
albumart.addEventListener('load', function () {
var vibrant = new Vibrant(albumart);
var swatches = vibrant.swatches()
for (var swatch in swatches)
    if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
        darkvibrant = swatches.DarkVibrant;
    }
});

Now can be used in the second function.

Another way is that you can assign the property on the window object like window.darkvibrant and use it with the same syntax in the second function:

albumart.addEventListener('load', function () {
var vibrant = new Vibrant(albumart);
var swatches = vibrant.swatches()
for (var swatch in swatches)
    if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
        window.darkvibrant = swatches.DarkVibrant;
    }
});
Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34