Home > Blockchain >  Change button position by clicking event?
Change button position by clicking event?

Time:03-27

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 >
        <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?

CodePudding user response:

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 >
  <button id="flip-flop">Go</button>
</div>

CodePudding user response:

You need to use JavaScript:

var d = document.getElementById("button");
  d.addEventListener('click',function(){
  d.className = d.className   " move";
});

see demo: http://jsfiddle.net/LJHQW/3/

Or, if you're already using jQuery:

$('.button').click(function(){
 $(this).addClass('move');
});

see Demo: http://jsfiddle.net/LJHQW/1

  • Related