So this is my first attempt at JavaScript (learning Java atm) and I’m almost finished. What I want to do is: Remove readonly from my textarea at page refresh, and after some minutes set it to readonly with timer.
All the timers, getElement-parts, and readOnly-attributes seem to be working (finally).
JavaScript:
<script>
//x = Timelimit in minutes, z = Time remaining alert in minutes
function timeLimit(x,z) {
var min = 60 * 1000;
var limit = x * min;
setTimeout(function(){ alert("Du har " + z + " minutter igjen på prøven.") },( limit - (z * min) ));
setTimeout(function(){ alert(x + " minutter har gått.\nTiden er slutt.") },limit);
setTimeout(document.getElementById('testroom').setAttribute('readOnly','readOnly'),limit);
}
</script>
Here’s the call for my function (put it below my textarea since it seemed to be the only way for getElement to find my textarea by id):
<form method="post" action="insert.php" />
<textarea name="content" id="testroom"></textarea><br>
<input type="submit" value="Send inn for retting" />
</form>
<script>
timeLimit(0.2,0.1);
document.getElementById('testroom').removeAttribute("readOnly",0);
</script>
If I move the removeAttribute above the timeLimit() (or put it inside the function), my textarea will stay readonly=true. If I put it below, it will stay readonly=false, even after 12 seconds (0.2 minutes, where the timer is supposed to happen).
Hopefully someone can clear this up for me, been searching a trying a lot of different syntax.
Your third setTimeout() call is not doing what you want. Instead it is executing the .setAttribute() method immediately. You should wrap it in a function to get it to execute later.
Even better, you could combine the two, but make sure to put the setAttribute call first so the user can’t sneakily kill your JavaScript at a bad time: