Steps to modify the border style upon clicking expand or collapse functionality

I'm working on a button that should expand when clicked, remove the bottom border, and then restore the bottom border upon collapsing. I've created a function to handle this behavior, where each click increments a counter. The goal is to show the border when the count is divisible by 2. However, despite my code below, it's not functioning as expected.

<script>
 function hideBorder() {
      var count = 0;
      var btn = document.getElementById("chi");
      
      if (btn.onclick) {
        count++;
      }

      if (count % 2 == 0) {
        document.getElementById("chi").style.borderBottom = "2px solid #65daff";
        document.getElementById("chi").style.borderEndEndRadius = "10px";
        document.getElementById("chi").style.borderEndStartRadius = "10px";
      } else if (count % 2 == 1) {
        document.getElementById("chi").style.borderBottom = "none";
        document.getElementById("chi").style.borderEndEndRadius = "0px";
        document.getElementById("chi").style.borderEndStartRadius = "0px";
      }
    }
</script>

Answer №1

By placing the count variable within the function, its value resets to 0 each time the function is invoked. To correct this, we can easily resolve it by relocating the declaration of count outside of the function to make it "global".

Answer №2

let counter = 0;
function toggleBorder() {
  let button = document.getElementById("chi");
  if (button.onclick) {
    counter++;
  }
  if (counter % 2 === 0) {
    button.style.borderBottom = "2px solid #65daff";
    button.style.borderEndEndRadius = "10px";
    button.style.borderEndStartRadius = "10px";
  } else if (counter % 2 === 1) {
    button.style.borderBottom = "none";
    button.style.borderEndEndRadius = "0px";
    button.style.borderEndStartRadius = "0px";
  }
}
<button id="chi" onclick="toggleBorder()">click</button>

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

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

Combining CSS and JavaScript to handle two events with a single onClick

Here is the code I've created: <a href="#" id="home" class="showLink" onclick="showHide('example');return false;"> <li class="buttons">home</li> </a> <a href="#" id="user" class="showLink" onclick="showHide(&a ...

An effective method for transferring form input and music between pages utilizing JavaScript

I've been grappling with this issue for quite some time now. On the initial page, I have a form like this: <form id="user" name="user" method="GET" action="the-tell-tale-heart.html"> Name: <input type="text" name="name"> & ...

Utilize parameters in Ajax's success function to analyze data retrieved from Django's backend

I'm currently working on a Django project where I am trying to handle a form using ajax. I have set up an ajax request to a Django view and receiving the response in JSON format. However, when I attempt to apply if-else conditions on the data, it alwa ...

Utilize state objects and child components by accessing sub-values within the object

I have a Dropzone component where multiple uploads can happen simultaneously and I want to display the progress of each upload. Within my Dropzone component, there is a state array called uploads: const [uploads, setUploads] = useState([]) Each element i ...

Image is not showing up on the Carousel

I seem to have a problem with my carousel as the images are not showing up when the webpage initially loads. The issue arises in Dreamweaver where the JavaScript function only works after clicking on one of the arrow buttons. I believe that I might need to ...

When the JSON array is converted into a string, it appears as undefined

Below is a snippet of my service.spec.ts file: service.spec.ts it('should mock the http requests', inject([Service, MockBackend], (service, mockBackend) => { let result:any; mockBackend.connections.subscribe((connection) => { ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Conflicts with FullCalendar - Dealing with Popovers and Over

I am currently using FullCalendar v6 with the resourceTimeGridDay feature. Within the 'eventDidMount' event render hook, I have implemented a JS function to display popovers on each event for showing event details. The popover is set to appear o ...

Creating a multi-tiered cascading menu in a web form: Harnessing the power of

In my form, there is a field called 'Protein Change' that includes a multi-level dropdown. Currently, when a user selects an option from the dropdown (for example, CNV->Deletion), the selection should be shown in the field. However, this funct ...

As I go through the database, I notice that my div model functions correctly for the initial record but does not work for any subsequent ones

I came across a model on w3 schools that fits my requirements, but I am facing an issue where the model only works for the first result when looping through my database. It's likely related to the JavaScript code, but I lack experience in this area. C ...

Is it possible to utilize the defineProperty accessor in JavaScript to modify the .length property of an array?

I am interested in setting an accessor on an array's length using Object.defineProperty() for academic purposes. This would allow me to notify for size changes dynamically. While I am familiar with ES6 object observe and watch.js, I prefer exploring ...

Is it possible to accept user input in order to customize the color of my object in Three.js?

// Retrieving the mesh and integrating it into the scene. var loader = new THREE.JSONLoader(); loader.load( "models/cubic.js", function(geometry){ // var material = new THREE.MeshLambertMaterial({color: 0x55B663}); alert(geometry.faces.length); //for ...

Trigger the mousedown event every 0.2 seconds, continuously, until the mouse is lifted

I'm attempting to dynamically increase the value of a text input field by +1 each time the user clicks a button. In a simple explanation, my JQuery code looks like this: $('#button').on({ mousedown : function () { var value = $(this).val ...

Tips for adding a picture to a server and applying CSS filters to enhance it

I recently came across a set of CSS filters that can be applied to images by simply specifying the filter ID. Now, I'm looking to create a button that will allow me to save the edited image (with the filter applied) to a designated file location. I&a ...

After making a POST request, the `Req.body` is assigned to

This is the JavaScript code I am using: app.use(express.static(__dirname)); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // support json encoded bodies app.get('/', function(req, res){ res.sendFile(__dirn ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

Utilize the HTML img tag in conjunction with AngularJS and Ionic to showcase dynamic images

Currently, I am working on a hybrid mobile app using ionic and Angularjs. I am facing an issue with displaying images through the img html tag in my app. The main layout of my page includes a carousel at the top that displays images and a list containing s ...

Error 107 occurred while attempting to parse JSON data using the AJAX technique with the REST API

I've encountered an issue while attempting to utilize the Parse REST API for sending push notifications. Every time I make an AJAX call, I receive an invalid JSON error in the response and a status code of 400. Below is my request: $.ajax({ url: & ...