Javascript number divider.

I did some more experimenting with Javascript in hopes of being able to enter any number and have the script divide that number by 2. I wanted to have such a script handy for helping me calculate the time remaining until my lunch break or the end of my shift, whichever comes first. By dividing that remaining time by 2, I can calculate the halfway point towards my next break. For example, if there’s 90 minutes until my lunch break, I would divide 90 by 2 to get 45 minutes, so that if I work 45 minutes, I only have another 45 minutes to go before my break. That helps the day go by faster.

Unfortunately, the computer I use at work has Windows XP with Internet Explorer 8, so I’m unable to implement some of the newer features of Javascript. This following script won’t work on browsers newer than Internet Explorer 8 but it works well enough for me to use on the job.

<!DOCTYPE html>
<html>
<body>
<input type=”number” name=”x”><p>
<button onclick=”myFunction(x)”>Do It!</button>
<p id=”demo”></p>

<script>
function myFunction(x)
{
var demoP=document.getElementById(“demo”)
demoP.innerHTML=”= ” + x.value/2;
return y;
}
</script>

</body>
</html>

This script gives you a small form box for entering a number and when you click “Do It!”, it divides that number by 2 and displays the result.

By changing the mathematical operation in the “demoP.innerHTML=”= ” + x.value/2;” line, I am able to use this script as a solid template for creating other scripts that do simple calculations such as converting minutes to hours.

I’m not ashamed to admit I’m still a novice when it comes to Javascript. The secret is taking advantage of online tutorials such as the ones at W3Schools and doing some fearless experimenting. When creating simple scripts like the one above, the worst that can happen is the script not running at all.

Advertisements

Tags:

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: