Is it possible to alter the location of a button through a click event

On the left side of the container, there is a button with the text "Go Right!". When clicked in this position, the button moves to the right side of the container. When the button is on the right side, the text changes to "Go Left!" and clicking it will move the button back to the left side.

I have attempted the following: 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

After running this code, the button does move to the right (perhaps after the second click) but it is not responsive. How can I restrict the movement to just until the right side of the container?

Answer №1

There are a few issues that need addressing.

  1. It's not ideal to add a click listener every time the button is clicked. Instead, add just one listener that performs the required task.

  2. Avoid using element.style as it creates inline styles, which are generally considered bad practice. It's better to define a CSS class in your stylesheet with the desired styles and toggle that class on click.

  3. To align the button to the right, simply set text-align: right on the button's parent element in this scenario.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue with HTML5 video tags on iPhone Safari is that 'a' links are not functioning correctly

For my mobile website in Safari browser, I am utilizing the html5 video tag. While the video is functioning properly, I have encountered an issue with 'a' links overlapping on top of the video. These links have been added using absolute positioni ...

The hamburger menu in Bootstrap collapses along with the navigation items when viewed on a mobile device

How can I resolve the issue of the hamburger menu icon collapsing with the nav-items when clicked? Navbar <header> <div class="container-fluid"> <div class="row"> <div class="col-12 col-sm-12"> ...

The backend is serving HTML content, but the frontend is not initiating any redirects

After hitting an API endpoint and examining the network call responses, I identified that the HTML response returned with a status code of 302. Despite this, I am perplexed as I do not witness the expected redirect on the user interface. The intended redir ...

Adjust the width of the dropdown menu to match the size of the input box

Within my input box in Bootstrap 4, there is a dropdown button located on the right. Upon clicking the button, a dropdown-menu is displayed. Inside the menu, there is an Angular component containing a table. <link rel="stylesheet" href="https://stack ...

What's the reason for the inability to resize fieldset using both?

Can someone explain why the resize control is not enabled on the fieldset element? The documentation mentions that resize does not work with: Inline elements Block elements that have overflow set to visible fieldset { resize: both; overflow: h ...

Retrieve the CSV file following a successful POST request

Is there a way to automatically download a CSV file upon clicking a button that triggers a post request? The post request generates a large response, making it inefficient to transfer it directly from express to the front end. I'm looking for a solu ...

Encountered a Server Error: Invalid hook call. Hooks are restricted to being called within the body of a function component specifically in _app.js

As someone new to React and Next JS, I am facing an issue with setting initial auth user data on the initial load from the __app.js file. Whenever I try to use dispatch, it throws an error saying "Invalid hook call". I understand that calling hooks in the ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Can you explain the function of a digest attribute?

As a beginner in the world of NextJS, I am currently working on getting my first project ready for production. However, I encountered the following error: Application error: a client-side exception has occurred (see the browser console for more information ...

Expanding file input fields in Javascript

I am facing an issue with my form and file input. I need to select images from a different folder. echo '<pre>'; var_dump($_FILES); echo '</pre>'; Upon submitting the form, only the last selected image is displayed, but I ...

Issue with NPM Scripts Post Hook Triggering

Currently, I am exploring the use of npm scripts to gradually phase out my dependency on Gulp. To begin, I have created a single custom script called watch. This script will eventually execute all other scripts prefixed with the name watch, such as watch:s ...

What is the best way to retrieve a table from an HTML page and convert it into a data frame using XML and Rcurl in R programming?

Can someone help me convert a table on the Forbes website into a data.frame? Click here to access the table ...

The height of the navigation bar adjusts to fit the image

I'm currently struggling with my html and css learning project. The height of the navigation bar is not adjusting properly to the size of the image. I have tried various solutions, but nothing seems to work. Any guidance would be appreciated! htm ...

Learn how to utilize Selenium Web Driver with Java to interact with waypoints located within a map canvas on an HTML5 webpage

Struggling with Selenium Web Driver (Java) - How to interact with waypoints on an HTML5 canvas map? I am currently trying to implement drag and drop functionality on a canvas map within an HTML5 page, but I'm facing some challenges. https://i.sstati ...

Error 403 with Google Search Console API: Access Denied

Currently, I am attempting to extract data from the GSC Search Analytics API using Python. Despite diligently following this resource, I have encountered an error that persists despite multiple attempts to remedy it: raise HttpError(resp, content, uri=se ...

Unusual Encounters with Firefox and Websockets

Situation: WebSockets are being utilized with JavaScript and the Play! framework (version 2.2). Data can be successfully sent and received in Chrome. In Firefox, data can only be received from the server as the send() function does not trigger any callba ...

placed three blocks inside the table cell

Is there a way to align three blocks in the table-cell layout so that p1 is at the top, p2 is at the bottom, and p3 is in the middle? Here is the corresponding HTML: <div id="table"> <div id="row"> <div id= ...

How about a single-page application that utilizes PHP for logging in?

Currently, I am working on a single-page application using React and Relay. In my application, I have various components that are either different or completely absent if the user is not logged in (such as a logged-in user dropdown menu, profile page, acc ...

Creating a JavaScript alert in Selenium Java WebDriver with a concise message

While running a Selenium Java program, I am attempting to create a JavaScript alert window with a specific string message. I came across a method that involves executing JavaScript within Selenium by interacting with hidden elements: WebDriver driver; Java ...

When it comes to JavaScript, the evaluation order of arguments and delayed evaluation play a crucial

Assuming function( arg1, arg2 ), is it true that arg1 will always evaluate before arg2 (unlike traditional C)? Is there a way to create a function where arguments are not evaluated immediately, but only on demand? For instance, in if( cond1 || cond2 ), c ...