Search code examples
javascriptcssmargin

Dynamically Allocating CSS Margin


How can we set the margin property dynamically i.e. i have to change the values of margin during the execution time. My aim is that i have to change the margin after every input and the new margin value is stored in y variable

<script>

function myFunction() {
 var y=document.getElementById("enter").value;
 document.getElementById("myDiv").style.marginLeft = "y px";
}
</script>
<html>
<head>
</head>
<body>

<div id="myDiv">This is a div.</div>
<input id="enter">
<br>
<button type="button" onclick="myFunction()">Set left margin</button>

   

</body>
</html>

How can we set the margin property dynamically i.e. i have to change the values of margin during the execution time. My aim is that i have to change the margin after every input and the new margin value is stored in y variable and i have to set the margin as y how can i do this


Solution

  • Replace "y px" with y + "px".