Skip to content
Advertisement

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?

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement