user10629012
user10629012

Reputation: 309

Variable in Jquery not defined in javascript

I have 2 pieces of code, one jQuery which checks the value of an input field and then takes this value a manipulates the CSS relatively. I have some vanilla Javascript and I was looking to use my jQuery to manipulate the JS as the jQuery is outside code block. How would I able to use the variables inside the jQuery in my vanilla Javascript?

$(document).ready(function() {
  $('input').change(function() {
    var val = $(this).val();
    var inputNo = (10 / val);
    if (val > 0) {
      $(".orb").addClass("rotating");
      $('.rotating').css("animation", "rotating " + inputNo + "s linear infinite");
    } else {
      $(".orb").removeClass("rotating");
    }
    console.log(inputNo);
  });
});

function init() {
  ctx.shadowColor = "#57e0c1";
  ctx.shadowBlur = inputNo;
  for (var i = 0; i <= totalTentacles - 1; i++) {
    lines[lines.length] = new Line();
  }
  animate();
}
init();

Upvotes: 1

Views: 68

Answers (1)

XaxD
XaxD

Reputation: 1538

The variable is scoped within the $('input').change function. This essentially means it disappears when the function ends. If you want it to be accessible to multiple function, you need to initialize it outside the function.

Eg.

var inputNo = 0; // declared outside function block

$(document).ready(function() {
  $('input').change(function(){
    var val = $(this).val();
    inputNo = (10 / val);
        if (val > 0) {
            $(".orb").addClass("rotating");
            $('.rotating').css("animation","rotating "+ inputNo +"s linear infinite");
        }
        else {
            $(".orb").removeClass("rotating");
        }
        console.log(inputNo);
  });
});


function init() {
  ctx.shadowColor = "#57e0c1";
  ctx.shadowBlur = inputNo;
  for (var i = 0; i <= totalTentacles - 1; i++) {
    lines[lines.length] = new Line();
  }
  animate();
}
init();

Note, there are deeper issues in your code however than simple variable scoping. For example, your init function will need to be called again within the change function if you want to update the shadow-blur on change as well.. so replace console.log(inputNo); with another init(); call.

Upvotes: 1

Related Questions