Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Change button position by clicking event?

There is button is on the left side of its container, with the text Go Right!. When the button is on the left side, clicking it results in the button moving to the right side of the container. When the button is on the right side, the button text is Go Left! When the button is on the right side, clicking it results in the button moving to the left side of the container.

I tried this: html:

<body>
    <div class="container">
        <button id="flip-flop" onclick="moveRight()">Go Right!</button>
    </div>
</body>

js file:

function moveRight(){
    const flip_flip_button = document.getElementById("flip-flop")
    flip_flip_button.addEventListener("click", function () {
       flip_flip_button.style.left = 400 + "px";
    });
}

css:

.container {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 50%;
    background-color: gray;
    transform: translate(-50%, -50%);
}

#flip-flop{
    position: relative;
}

image

This code result, the button is move right (by second click? don't know why also) but not responsive.How can I move right button just until container right side?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Several problems here.

  1. You are adding a click listener every time the button gets clicked. Instead, only add one listener, that does the actual work you want.

  2. Don't work with element.style, as that produces inline styles, which are widely consider very bad practice. Instead, prepare a CSS class in your CSS that contains the desired styles, and toggle that class on click.

  3. In this case the easiest way to get your button aligned to the right is setting text-align: right on the button's parent element.

document
  .getElementById('flip-flop')
  .addEventListener("click", function() {
    this.parentNode.classList.toggle('right');
  });
.container {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 50%;
  background-color: gray;
  transform: translate(-50%, -50%);
}

#flip-flop {
  position: relative;
}

.right {
  text-align: right;
}

#flip-flop::after {
  content: " right!";
}

.right #flip-flop::after {
  content: " left!";
}
<div class="container">
  <button id="flip-flop">Go</button>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!