Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I add accumulative Margin on button click?

I am trying to add a text slider, where basically a very long text box extends out of the view, and when a button is pressed margin is added so more text can be read. I do not know how to make a button that adds margin without exponentially increasing it each time.

<div class='long'>
  <div class='container'>
          <button type="button" onclick="display()">Add left margin</button>
  <p id="myID">This is demo text.</p>
  <script>
     function display() {
        var e = document.getElementById("myID").style.marginLeft += 1  document.getElementById("myID").style.marginLeft; 
     }
  </script>

After a few clicks, this starts to increase the margin insane amounts. I believe it is because the 1 is not 1px, but some other unit which makes it add up insanely quick. SO I want to have a button that adds 1px of margin per click, so it smoothly adds margin instead of a big unuseable jump.

My hypothesis is that you need to get the margin value, store it, then add it to a string that has ‘px’ at the end then update the margin with it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are correct with your thoughts. Store the margin value in a variable outside the function, and increase it by one each time.

The style.marginLeft returns 1px and not 1 which means you cannot increment to it.

var margin = 1; 
function display() {
    document.getElementById("myID").style.marginLeft = ++margin + "px";
}
<div class='long'>
  <div class='container'>
          <button type="button" onclick="display()">Add left margin</button>
  <p id="myID">This is demo text.</p>
  </div>
  </div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading