How to pass javascript function variable to a differet javascript function?

Viewed 54

I want to use the 'output.innerHTML' to the 'generatePassword' function.

function sliderControl() {
    var slider = document.getElementById("slider");
    var output = document.getElementById("output");
    output.innerHTML = slider.value;
    slider.oninput = function() {
        output.innerHTML = this.value;
    };
}
sliderControl();

function generatePassword(length = "I WANT TO USE THAT VARIABLE HERE") {}
5 Answers

You can return output.innerHTML

function sliderControl() {
    var slider = document.getElementById("slider");
    var output = document.getElementById("output");

    slider.oninput = function() {
        output.innerHTML = this.value;
    };
    output.innerHTML = slider.value;
    return output.innerHTML;
 }
const val = sliderControl();

function generatePassword(val) {}

You can add a new variable.

function sliderControl() {
var slider = document.getElementById("slider");
  var output = document.getElementById("output");
  output.innerHTML = slider.value;
  slider.oninput = function () {
    output.innerHTML = this.value;
    return output.innerHTML;
  };
}
var yourVariable = sliderControl();

function generatePassword(yourVariable) {
    // do the thing with yourVariable
}

You could use the output.innerHTML like you have set it.

function sliderControl() {
  let slider = document.getElementById("slider");
  let output = document.getElementById("output");
  output.innerHTML = slider.value;
  slider.oninput = function () {
    output.innerHTML = this.value;
  };
}
sliderControl();

function generatePassword() {
  let length = document.getElementById("output").innerHTML;
}

I would also recommend to use let instead of var inside closures and functions. As var might cause unexpected side effects, as it can change the value of a already declared variable of the same name outside the functions/closure.

There are a few ways to accomplish what you want. Personally I'd declare your elements outside of the function so you can reuse them:

const slider = document.getElementById("slider");
const output = document.getElementById("output");

// Add input event listener
slider.addEventListener('input', function(event)
{
    output.innerHTML = event.target.value;
});

function sliderControl()
{
    output.innerHTML = slider.value;
}

sliderControl();

// Pass length or use default variable value
function generatePassword(length = output)
{
}

Note: The reason why I've added the event listener outside of the function is because you only need to do that once. You usually don't declare a function if you intent to only use it once. If you were to use that function multiple times, it would keep on adding the event listener for no reason.

You can define the output variable outside the sliderControl function and then it is accessible across all of your functions, including generatePassword.

Related