Home > Enterprise >  How can I add accumulative Margin on button click?
How can I add accumulative Margin on button click?

Time:12-14

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?

CodePudding user response:

The parseInt and parseFloat functions will return numeric value for marginLeft (i.e. without the trailing 'px' that is causing your issue).

function display() {
    let el = document.getElementById("myID");
    el.style.marginLeft = `${parseInt(el.style.marginLeft) 1}px`;  
 }

CodePudding user response:

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>

CodePudding user response:

The problem is that happen string concatenation when you use the operator You have to convert the value returned from element.style.marginLeft to a number. You can call the Number() function or use the operator immediately attached how in my solution. Another problem could be that the value returned is like that 1px for example and to increment it you have to parse it, I used split function

function display() {
           let currentMarginValue =  document.getElementById("myID").style.marginLeft.split('px')[0];
           console.log(currentMarginValue)
          var e = document.getElementById("myID").style.marginLeft = currentMarginValue   1   "px" ;
       }

CodePudding user response:

you may need one counter that will increase in every click. please refer below code

  <script>
  let count = 0;
     function display() {
     document.getElementById("myID").style.marginLeft =   count "px";
     }
  </script>
  • Related