+ 1
randomize the margin
Hi everyone ! I need your help here. I would like to have random margin for each element in a class. Actually I can make the same random margin for all, using getElementsByClassName and Math.floor(Math random()). How can I make a "randomize" function that would be called by each element and apply to itself ? Thank you already ! Paul https://code.sololearn.com/WivGo6fAy4SP/?ref=app
5 Antworten
+ 5
In that case use this JS
function randomize(){
var r;
var list = document.getElementsByClassName("test")
for(var i=0;i<36;i++){
r = Math.floor(Math.random()*50);
list[i].style.margin = r + "px";
}
}
+ 2
you cannot make every HTML element to call a particular function using onload event because it works with only few which are as follows:
<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style>
//this will work for any numbe rof elements
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.test{
background-color:red;
}
</style>
</head>
<body>
<div class="test">wesh</div>
<div class="test">yo</div>
<div class="test">bitezer</div>
<script type="text/javascript">
var element=document.getElementsByClassName("test");
for(var i=0;i<element.length;i++)
{
randomize(element[i]);
}
function randomize(ele)
{
var marginValue=Math.floor(Math.random()*50);
ele.style.margin=marginValue+"px";
}
</script>
</body>
</html>
0
Hi there,
If you want to set random margin for all element use this JS
function randomize(){
setRandomMargin("test0");
setRandomMargin("test1");
setRandomMargin("test2");
}
function setRandomMargin(id){
var rdm=Math.floor(Math.random()*50);
var item=document.getElementById(id);
item.style.margin= rdm + "px";
}
I hope this will help you
0
thanks ! but how can I make it more methodic (i want to use it on a class with 36 elements) ?
0
great !! thanks a lot !