The div in JavaScript is expanding properly, but it is not contracting back as expected

I'm experiencing an issue with a div element that I created. My goal is to have it expand when a link is clicked and collapse when the same link is clicked again. At the moment, the div expands correctly but does not collapse as expected. Any assistance would be greatly appreciated.

<script>

        function setDisplay()
        {
            document.getElementById('divCollapse').style.display="none";
        }

        function expandSelected()
        {
            if(document.getElementById('divCollapse').style.display="none")
            {document.getElementById('divCollapse').style.display="block";}

            else if(document.getElementById('divCollapse').style.display="block")
            {document.getElementById('divCollapse').style.display="none";}

        }
    </script>

Answer №1

Ensure you are using == for comparing values in your if/else if statements, not = which is used for assignment.

<script>

    function setDisplay()
    {
        document.getElementById('divCollapse').style.display="none";
    }

    function expandSelected()
    {
        if(document.getElementById('divCollapse').style.display=="none")
        {document.getElementById('divCollapse').style.display="block";}

        else if(document.getElementById('divCollapse').style.display=="block")
        {document.getElementById('divCollapse').style.display="none";}

    }
</script>

Answer №2

= is commonly used as an assignment operator.

If you want to compare values, use ==.

Here's a simple example:

function toggleVisibility() {
   if(document.getElementById('toggleElement').style.display == "none") { // Check here
      document.getElementById('toggleElement').style.display = "block";
   } else if(document.getElementById('toggleElement').style.display == "block") { // Check here
      document.getElementById('toggleElement').style.display = "none";
   }

}

To learn more about comparison operators, check out this resource.

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

Encountering an error while trying to update a field using the $inc operator in

Currently, I am working on updating a field in my database to increment it each time like a counter. This will allow me to consistently receive the latest values. To achieve this, I have defined the following schema: var CounterSchema = new Schema({ _id: ...

"Troubleshooting: Handling null values in a web service when using jQuery

The API located at http://localhost:57501/api/addDatabase contains the following code snippet: [System.Web.Mvc.HttpPost] public ActionResult Post(addDatabase pNuevaConeccion) { pNuevaConeccion.insertarMetaData(); return null; ...

Next.js React Server Components Problem - "ReactServerComponentsIssue"

Currently grappling with an issue while implementing React Server Components in my Next.js project. The specific error message I'm facing is as follows: Failed to compile ./src\app\components\projects\slider.js ReactServerComponent ...

AngularJS - Ng-Table - Undefined

I'm facing difficulties when trying to create an ngTable. I can successfully render manually created arrays, but when I connect it to my api, it fails without any error message which is confusing. The $scope.data array is being filled as expected, but ...

Django Accordion Table Template

I have a Django model that populates a table with objects from a database. What I'm trying to achieve is, when a row in the table is clicked, to use JS or JQuery to accordion a table of objects that are connected as foreign keys to the main object. A ...

Implementing JavaScript to showcase a list extracted from an API dataset

I'm currently undertaking a project where I am integrating an API from a specific website onto my own webpage. { "data": [{ "truckplanNo":"TCTTV___0D010013", "truckplanType":"COLLECTION", " ...

Can you explain the distinction between $and and $all in this specific scenario?

These two lines of code may seem similar, but is there a crucial difference between them? I understand the importance of documentation, but in this specific scenario, what sets them apart? Thank you for your insights! db.someData.find({$and: [{genre: {$eq ...

Tips for passing a variable from one function to another file in Node.js

Struggling to transfer a value from a function in test1.js to a variable in test2.js. Both files, test.js and test2.js, are involved but the communication seems to be failing. ...

Is there a way to export all images that have been imported into a React JS file with just one export command?

In the process of developing a solitaire game using React, I have implemented a Card component that displays a card on the screen based on its suit and number. Inside the Card.js file, there are several imports for image sources, such as: import cardFrontT ...

Pressing the CTRL key and then the PLUS key simultaneously activates the zoom in

Is there a way to capture Ctrl + + / Ctrl + - events in Firefox using the following code: window.onkeydown = function(event) { if(event.ctrlKey && event.keyCode == 61) CtrlPlus(); if(event.ctrlKey && event.keyCode == 169) // or ...

Enhance user experience with HTML-tags in tooltips

Is there a way to display a tooltip in Twitter Bootstrap that includes HTML tags for formatting? Currently, I am using the following code: <a class="my-tooltip" rel="tooltip" href="#" data-original-title="CPR + O<sub>2</sub>.">First-Aid ...

What could be the underlying reason for the unusual behavior observed in this range polyfill implementation?

I am attempting to transform an HTML5 range input into a set of radio buttons. Each radio button corresponds to a value within the original range, with text displaying its value. However, I am encountering an issue where the last piece of text, meant to sh ...

Is there a way to prevent the use of any keys other than letters and numbers in the search input field of a datatable, such as function keys or shortcut keys?

jQuery Query: Is it possible to trigger the search function only when alphabet and number keys are typed? For DataTables, global searching should only start when at least 3 characters have been entered. $(document).on('draw.dt','.dataTable ...

Sending a JavaScript variable to PHP and retrieving the PHP result back into a JavaScript variable

I am looking to transfer a JavaScript variable to a PHP file using AJAX, and then retrieve the PHP file's output back into a JavaScript variable. For sending the JavaScript variable to the PHP file, I found a method that suggests using ajax to assign ...

Utilizing Binding Time in Angular for Enhanced Views

I am completely new to Angular JS. I have a simple question that I have been searching for answers on SO. My goal is to display the current time in real-time (refreshing every second as the clock ticks) on my view. Here's what I have tried so far: H ...

Retrieving a list from a C# function using JQuery ajax

I find myself in a bit of a dilemma while attempting to integrate C# and jQuery seamlessly. Within the same solution/project, I have a .cs file and a javascript document. The C# function I've written returns a list of strings, which I aim to append to ...

What is the best way to set up TypeScript to utilize multiple node_modules directories in conjunction with the Webpack DLL plugin?

Utilizing Webpack's DllPlugin and DllReferencePlugin, I create a distinct "vendor" bundle that houses all of my main dependencies which remain relatively static. The project directory is structured as follows: project App (code and components) ...

Clicking on AngularJS ng-click to navigate to a different page within an Ionic framework application

My goal is to navigate to another page when clicking on a button in the Ionic navbar at the top. However, I am encountering an issue where upon clicking, all nav bar buttons disappear. Interestingly, using dummy codes triggers an alert successfully. But w ...

Is it possible to implement marker dragging in Google Maps v3 using JavaScript? How can this be achieved?

I am currently using this code to search for an address, drop a marker, and drag it afterwards. <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title&g ...

During the execution of my asynchronous javascript, it interrupts the flow of the other function

How can I ensure that a function executes after another one in Vue.js? I've tried various methods like async/await, callback functions, and .then, but none seem to work seamlessly. Any suggestions for a possible solution? auth_util.js: async auth () ...