0

First post, sorry if i'm doing this wrong.

var tierArray = [390, 520, 750, 975, 1350, 1820, 3250];
var rand = Math.floor((Math.random() * 6) + 1);
var rp;
var skinName = document.getElementById("skinName");
var skinRP = document.getElementById("skinRP");
var totalRP = document.getElementById("totalRP");
var totalMG = document.getElementById("totalMG");
var total = parseInt(totalRP.value);
var mg = parseInt(totalMG.value);

var array390, array520, array750, array975, array1350, array1820, array3250 = [];
var skinImg = document.getElementById("skin");
var activeArray;

function roll() {
    mg += 490;
    rp = tierArray[rand];
    total += rp;

    skinName.value = "hello";
    skinRP.value = rp;
    totalRP.value = total;
    totalMG.value = mg;
}

My page worked before moving all my variables to a global scope so that they were usable to other methods, now they have been moved the code doesn't run, and my JSLint is not picking up a problem, am i missing something?

Liam Morgan
  • 136
  • 2
  • 13
  • what is the error in browser console? – gurvinder372 Mar 17 '16 at 14:06
  • What problem is JSLint picking up? And try to debug the script first to diagnose the problem. At first glance your script appears OK – Jodi Supporter Mar 17 '16 at 14:06
  • were your variables earlier in global scope? what is error you are getting now? – S4beR Mar 17 '16 at 14:07
  • 1
    My crystal ball tells me that you're not finding the elements using `getElementById` because this code is now running during page load before those elements are available, whereas before it wasn't until the `roll` function was called at some later point. See [this Q&A](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) for more information. – James Thorpe Mar 17 '16 at 14:09
  • `document.getElementById("totalRP")` can return you a `null`, in this case `totalRP.value` will throw error – zooblin Mar 17 '16 at 14:09
  • James Thorpe is right, and so is zooblin. Now can anyone help me to fix these problems? i need them to be global but do not want them to be there on page load. – Liam Morgan Mar 17 '16 at 14:12
  • Its easy, put your – Randy Mar 17 '16 at 14:14
  • Add your code in a document ready method. [Here](http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the) is a nice explanation. – Deepak Biswal Mar 17 '16 at 14:22

1 Answers1

0

Your elements outside the functions are not loaded as you run your code, that probably is because you first implement your script to your page, and thén you insert your HTML DOM Elements.

<head>
<script>         < The elements dont exist
<body>
<element>        < The elements exist
<script>         < Your script
Randy
  • 9,419
  • 5
  • 39
  • 56