Sliding toggle switch requiring two clicks

I'm encountering a problem with a toggle button I'm trying to create. It only moves after two clicks, even though I know I need to set it before sliding on the first click. However, when I tried that, it clicked to the right and wouldn't move back no matter how many times I clicked it. Can anyone help me solve this issue?

`

    <div class="main">
        <div class="container">
            <div class="slider" id="slideHousing">
                <div class="slideBtn" id="slider" onclick="SlideRight()">

                </div>
            </div>
        </div>
    </div>

`

.main {
            display: table;
            height: 100%;
            width: 100%;
            border: 1px solid transparent;
        }

        .container {
            display: table-cell;
            vertical-align: middle;
            border: 1px solid transparent;
        }

        .slider {
            height: 100px;
            width: 200px;
            border-radius: 50px;
            background-color: #f2f2f2;
            margin: 0 auto;
            border: 1px solid transparent;
            
        }

        .slideBtn {
            border: 1px solid transparent;
            height: 95px;
            margin: 1px;
            width: 100px;
            border-radius: 50px;
            background-color: silver;
        }

`

function SlideRight() {
            // Checks to see if the slider is to the left of the div
            if (document.getElementById("slider").style.float === "left"){
                // If it is we will float the sliderBtn to the right and change the background of the housing to green
                document.getElementById("slider").style.float = "right";
                document.getElementById("slideHousing").style.backgroundColor = "#00ff00";

                // Toggle dark mode on
                document.body.style.backgroundColor = "#595959";
                document.getElementById("header").style.color = "#e6e6e6";
            } else {
                // If clicked again the btn will move back to the left side and change the color back to original
                document.getElementById("slider").style.float = "left";
                document.getElementById("slideHousing").style.backgroundColor = "#f2f2f2";

                // Toggle dark mode off
                document.body.style.backgroundColor = "#e6e6e6";
                document.getElementById("header").style.color = "#000";
            }
        }

Answer №1

When initially checking for style.float === 'left', the result is undefined since it hasn't been assigned a value yet. Instead, consider checking if the value is not equal to 'right' using style.float !== right.

function SlideRight() {

  // Verify if the slider is positioned to the left of the div
  if (document.getElementById("slider").style.float !== "right") {
    // Move the sliderBtn to the right and change background color to green
    document.getElementById("slider").style.float = "right";
    document.getElementById("slideHousing").style.backgroundColor = "#00ff00";

    // Enable dark mode
    document.body.style.backgroundColor = "#595959";
    document.getElementById("header").style.color = "#e6e6e6";
  } else {
    // Toggle the btn back to the left side and revert color changes
    document.getElementById("slider").style.float = "left";
    document.getElementById("slideHousing").style.backgroundColor = "#f2f2f2";

    // Disable dark mode
    document.body.style.backgroundColor = "#e6e6e6";
    document.getElementById("header").style.color = "#000";
  }
}
.main {
  display: table;
  height: 100%;
  width: 100%;
  border: 1px solid transparent;
}

.container {
  display: table-cell;
  vertical-align: middle;
  border: 1px solid transparent;
}

.slider {
  height: 100px;
  width: 200px;
  border-radius: 50px;
  background-color: #f2f2f2;
  margin: 0 auto;
  border: 1px solid transparent;
}

.slideBtn {
  border: 1px solid transparent;
  height: 95px;
  margin: 1px;
  width: 100px;
  border-radius: 50px;
  background-color: silver;
}
<div id="header">

</div>

<div class="main">
  <div class="container">
    <div class="slider" id="slideHousing">
      <div class="slideBtn" id="slider" onclick="SlideRight()">

      </div>
    </div>
  </div>
</div>

Although this is a good start, there are several suggestions that can be implemented:

  • The entire slider should be clickable
  • Rename the onclick event to something like slideToggle
  • Create a CSS class that automates the process

For example:

function toggleSlider(ele) {
  ele.classList.toggle('active')
}
.main {
  display: table;
  height: 100%;
  width: 100%;
  border: 1px solid transparent;
}

.container {
  display: table-cell;
  vertical-align: middle;
  border: 1px solid transparent;
}

.slider {
  height: 100px;
  width: 200px;
  border-radius: 50px;
  background-color: #f2f2f2;
  margin: 0 auto;
  border: 1px solid transparent;
}

.slideBtn {
  border: 1px solid transparent;
  height: 95px;
  margin: 1px;
  width: 100px;
  border-radius: 50px;
  background-color: silver;
}

.slider.active .slideBtn {
  float: right;
}

.slider.active {
  background-color: #00ff00;
}
<div id="header">

</div>

<div class="main">
  <div class="container">
    <div class="slider" id="slideHousing" onclick="toggleSlider(this)">
      <div class="slideBtn" id="slider">

      </div>
    </div>
  </div>
</div>

Answer №2

After adding this to your CSS:

  #slider {
          float: left;
        }

I made a slight adjustment by swapping the positions of "left" and "right" in all of your JavaScript code (since it is now initially set to left) and it appears to be functioning correctly:

function SlideRight() {
            // Checks if the slider is positioned to the right of the div
            if (document.getElementById("slider").style.float === "right"){
                // If so, move the sliderBtn to the right and change the background color of the housing to green
                document.getElementById("slider").style.float = "left";
                document.getElementById("slideHousing").style.backgroundColor = "#00ff00";

                // Activate dark mode
                document.body.style.backgroundColor = "#595959";
                document.getElementById("header").style.color = "#e6e6e6";
            } else {
                // If clicked again, move the button back to the left side and revert the color to its original state
                document.getElementById("slider").style.float = "right";
                document.getElementById("slideHousing").style.backgroundColor = "#f2f2f2";

                // Deactivate dark mode
                document.body.style.backgroundColor = "#e6e6e6";
                document.getElementById("header").style.color = "#000";
            }
        }
.main {
            display: table;
            height: 100%;
            width: 100%;
            border: 1px solid transparent;
        }

        .container {
            display: table-cell;
            vertical-align: middle;
            border: 1px solid transparent;
        }

        .slider {
            height: 100px;
            width: 200px;
            border-radius: 50px;
            background-color: #f2f2f2;
            margin: 0 auto;
            border: 1px solid transparent;

        }

        .slideBtn {
            border: 1px solid transparent;
            height: 95px;
            margin: 1px;
            width: 100px;
            border-radius: 50px;
            background-color: silver;
        }

        #slider {
          float: left;
        }
 <div class="main">
        <div class="container">
            <div class="slider" id="slideHousing">
                <div class="slideBtn" id="slider" onclick="SlideRight()">

                </div>
            </div>
        </div>
    </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 hyperlink is unresponsive and cannot be activated with a click

I encountered an issue with my website where I am unable to click on the href link. Oddly enough, the link works fine on my offline test version but once uploaded to the hosting server, it stops working. I have inspected the html and css coding on my webs ...

Steps to trigger a dialog to appear automatically within an Icon Menu with React Material UI

In my application, I have an icon menu implemented along with an array that contains the possible values for the items in the menu. Here is an example of how the array looks: listItems = { [ { label: 'ZERO', t ...

JavaScript: Troubleshooting Array Formatting

Seeking assistance with formatting this JavaScript array accurately. It seems like I am overlooking something crucial: Javascript: <script type="text/javascript"> var dimensions = new Array("225","320","480", "--"); var walls = new Array() ...

Creating an AJAX request in Knockout.js

Forgive me if this question has been asked previously, as my search attempts have been unsuccessful in finding a solution. Despite consulting the knockout documentation, I still struggle to articulate my issue effectively for searching. My situation invol ...

Navbar Dropdown Button in Bootstrap Not Functioning Properly

I've been utilizing Bootstrap to create a navigation bar, but the dropdown button is not functioning when clicked. What could be causing this issue? <!-- Website HEAD --> <head> <title> Celeb Live </title> <!-- Web ...

retrieve the classname by tapping into the parsed JSON

Being a newcomer to this technology, I am embarking on my first project. My task involves calling an API and receiving a large parsed JSON file. Within this extensive JSON response (which contains HTML code), I need to extract a specific class from the te ...

Vuetify: how to disable the color transition for v-icon

My menu includes both icon and text items, with hover color styled using the following CSS: .v-list-item:hover { background: #0091DA; } .v-list-item:hover .v-list-item__title, .v-list-item:hover .v-icon { color: white; } The problem is that the ...

Debugging issue with Mongoose find search in ExpressJS with an if statement

Welcome to our URL shortener project! app.get('/:url', (req,res) => { Url.find({userUrl:req.params.url},(err,doc)=>{ //checking if the link is already in the database if(err){ console.error(err) }else if(doc[0].userUrl==req ...

My component is not executing the onClick function as expected

I am facing an issue with a component that I imported into another component. Despite clicking on the component, the onclick function does not execute. Here is the code snippet for the component: const HomeFeedCard = ({ name, image, published, quantity, w ...

Not successfully integrating an angular component

In my Angular application, I am working on creating a new component and injecting it into the app. Below is the code for the angular component: (function(angular) { 'use strict'; angular.module('some.someModule', ['bm.component.t ...

Assign a value to a dropdownlist in Javascript

I am facing an issue with setting the selected value of a dropdownlist that is populated by a webservice using ajax cascading dropdown. It seems like the values are not available when the javascript code runs, even though I have placed it at the bottom o ...

Place the image over another section, shifting the content aside

Current: http://jsfiddle.net/nmd1abot/ Desired: https://i.sstatic.net/RP5z7.jpg Basic structure Section Header Body Graphic Section Header Body I'm looking for a way to make the graphic overlap into the grey section while provi ...

Prevent removal in jQuery Sortable by confirming first

How can I prevent the sorting of items if a confirmation box is denied in a remove function? Below is my sortable unordered list implementation. $("#items").sortable({ remove: function(event, ui) { var id = ui.item.attr("id"); var loadUr ...

Using Three.js with an HTML slider

I am facing an issue with integrating Three.js and an HTML slider. Although the slider appears on the screen, it remains unresponsive to any attempts to move it. Dragging to change the value does not have any effect, instead only causing movement of the ca ...

Create a JavaScript function that checks for the existence of a file and returns a

I need to implement a JavaScript function that can determine if a file exists on a web server by using the fetch() method. Below is my current code snippet: let result = checkFile("index.html"); console.log("typeof(result) = " + typeof(result)); async fu ...

Stationary element against backdrop

I am attempting to create a footer that subtly emerges from behind the div element above it. One example is the layout of the Pitchfork website, where the footer sits at the bottom of the page. In my CSS attempt: #footer { overflow: hidden; } #foote ...

Steps to manage the time delay between mousewheel events triggering

Currently, I am working on a website for a movie production company that showcases their various films in full-screen mode. Each video is listed and there is a function that automatically takes the user to the next video when a mousewheel event occurs. How ...

Using NodeJS: Transmitting parameters and the current object to event handlers

After skimming through the NodeJS documentation on event handling at https://nodejs.org/api/events.html, I find myself a bit perplexed by how this is managed in event listeners: “While ES6 Arrow Functions can be utilized as listeners, it's worth no ...

Getting some clarity on how to structure a project using Node.js, Express.js, and React.js

I am in the process of developing a website for online shopping purposes, essentially an e-commerce platform. However, I am facing a dilemma where create-react-app sets up its own Node.js server to communicate with my backend (which handles MySQL queries) ...

Upon loading, the IntersectionObserver immediately declares the isIntersecting property true for all elements

Yesterday, when I executed this code, everything functioned as expected. The observer successfully loaded the images once they intersected the viewport: <template> <div id="gallery" class="gallery"> <div class=" ...