Modulus % of a division

We can get modulus of a any two numbers in JavaScript by using % . This gives us the reminder after a division. For example let us find out modulus of 23 and 5. Here is the sample.
var x=123%5;
document.write(x);
Output is 3

Similarly the following code will give output of 0
var x=12%2;
document.write(x);

Example : Using modules to reset an incremental counter

We will display on incremental counter by showing the value increasing from 0 to 29. The counter will increase by 1 after every second and on 30th second it will reset to 0.

setTimeout(), the timer function

Here modulus will be used to check the accumulated value to be divisible by 30 (highest counter value) or not.
DEMO : Incrmental Counter using Modules to reset with script

Example : Changing background color of alternate elements of an array

Using this we can develop one application where alternate rows background color can be changed. We have seen how to display elements of an array here. Now by using modulus function we will make alternate array elements background colour to different one.

Here the variable i will have incremental numbers on each loop. By dividing it with 2 we will get reminder either zero or one alternately. So we can change the display of background colour by html span tag. Same way we can add each row background colour if we use a table to display elements.

Here is the code
<script type="text/javascript"> 
function disp_data(){
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
var str="";
for (i=0;i<scripts.length;i++)
{
if((i%2)==0){
str += scripts[i] + "<br >" ;
}else{
str += "<span style='background-color: #FFFF00'>" + scripts[i] + "</span><br >";
}
document.getElementById("a2").innerHTML= str;
}
}
</script>

<input type=button value='Display Array' onClick='disp_data()';> 
<div id='a2'  style=" background-color: #c0f0c0; width:200" > Array elements</div>
Modulus is also called as modulo

Absolute value of integer
JavaScript Math Reference
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer