The else if statement is not functioning as anticipated

I am looking for a toggle function that will open and close a <div> when clicked. Check out this JSFiddle

HTML

<div class='answer'>answer</div>
  <div style='display:none'>
    <textarea name='talking'></textare>
    <input type='submit'>
</div>

JQuery

$('.answer').click(function(){
    if($(this).next().css('display','none')){
        $(this).next().css('display','block');
    }else if($(this).next().css('display','block')){
        $(this).next().css('display','none');
    }
})

In this scenario, the "if" statement works as intended to open the <div>, but the "else if" statement does not successfully close it again.

Answer №1

When crafting your conditional statements, it is important to access the element's display property and compare it with a specific value.

Instead of:

if ( $(this).next().css('display', 'none') ) {
    // ...
}

You should have:

if ( $(this).next().css('display') === 'none' ) {
    // ...
}

See Updated Example

$('.answer').click(function () {
    if ($(this).next().css('display') === 'none') {
        $(this).next().css('display', 'block');
    } else if ($(this).next().css('display') === 'block') {
        $(this).next().css('display', 'none');
    }
});

Your code can actually be simplified like so:

View Example Here

$('.answer').on('click', function () {
    $(this).next().toggle();
});

The .toggle() method streamlines this process for you.

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

Stop the submission of a form using jQuery based on its unique identifier

When using the jQuery Ajax function to verify if a user email exists in the database during a jQuery change event, there are two possible outcomes in the Ajax response. If the user email does exist, an error message is displayed. In this scenario, I aim ...

Check through an array for any updates whenever a function is called and my react state is altered

I am currently working on a project related to playlists. My goal is to display the image attached to each song whenever that song is clicked from the playlist. Here is the code I have so far... const Component = () => { const value = useContext(DataC ...

Unlocking the potential of # to craft interactive web pages

Lately, I've been seeing more and more websites like Twitter that have integrated AJAX into their layouts. One thing that has really piqued my interest is the inclusion of #! in URLs. I'm curious about how I can implement this on my own site or w ...

How can I make vuetify carousel arrows unique to my design?

Hey there, I'm currently working with this template in my application: <v-carousel cycle height="300" class="carousel" hide-delimiters> <template v-slot:prev="{ on, attrs }"> < ...

Initial variables for jQuery widget encryption setup

I have been searching for a viable solution to this dilemma for quite some time now, but I have yet to find any satisfactory answers. My goal is to develop a jQuery widget that customers can integrate into their websites. However, I need this widget to be ...

Is there a way to determine if a webpage is being accessed from a website or from a local file system?

While this question has been raised in the past, none of the answers provided seem to be accurate. Unfortunately, I am unable to comment on the original question or answers. Thus, following suggestions given to me, I have decided to create a new question. ...

What is the process for exporting a class and declaring middleware in TypeScript?

After creating the user class where only the get method is defined, I encountered an issue when using it in middleware. There were no errors during the call to the class, but upon running the code, a "server not found" message appeared. Surprisingly, delet ...

Interfacing with the data fields of a native application using Node.js

After developing a native Android (Java) mobile application, I found myself needing to run a node.js server on the client side. Being new to this, I opted to utilize Node.js for Mobile Apps () in order to execute my index.js file. Following the provided in ...

What is the purpose of storing the Vue instance in a variable or constant?

As a newcomer to Vue, I've noticed that in many tutorials and documentation sources, the new Vue instance is often stored in a variable like app. I'm curious, what is the benefit of saving the Vue instance in a constant or variable? const app = ...

Extracting Querystring Value in C#

When using the code below to set the iframe src with JavaScript, everything works as expected. However, in the C# code behind, I am receiving the query string in a format like this: id=Y&amp%3bcust_id=100&amp%3. Is there a way to simplify this? v ...

Press the button in an HTML document to activate JavaScript

What could be the issue with my code? I have a button in HTML <a class="btn btn-warning btn-mini publish-btn" href="#" data-rowid="@computer.id" data-toggle="modal" data-target="#myModal">Outdated</a> and my modal <fieldset style="text-al ...

When first logging in, React context may initially return as undefined, but it functions correctly upon refreshing the

Currently, I am in the process of learning React Context and implementing it on a Higher Order Component (HOC) to maintain user login status throughout my application. Upon successful login, I extract the user's name from the context and display it in ...

Code snippets to reduce excess white space on a website using HTML and CSS

On my website, there are multiple tabs, each containing content from an HTML file. When a user clicks on Tab1, boxes with images are displayed. The layout can be seen in the following Code Demo: Code Demo here There seems to be extra space before and afte ...

Using the map method to print from a massive array collection in sets of 20

Given a large array of numbers, I am attempting to divide it into sets of 20 numbers and print them. However, when I try to iterate through the array with an if condition, I get undefined values. I thought of creating a result array and pushing the subset ...

Unable to bring in the specified export 'Directive' from a non-EcmaScript module - only the default export is accessible

I am currently working on an ionic angular project and utilizing the ng-lazyload-image plugin. However, I am encountering errors during compilation that look like this: Error: ./node_modules/ng-lazyload-image/fesm2015/ng-lazyload-image.mjs 401:10-19 Can ...

What could be the reason why the color of pixels X and Y is not being retrieved successfully in this

Seeking to extract the color of pixel X,Y from an image using the code example provided in this response (). $('#map').mousemove(function(e) { if(!this.canvas) { this.canvas = $('<canvas/>') ...

What is the best way to add a background to text that has been wrapped?

How can I achieve a background effect for text that is wrapped within a container using CSS? Is it possible to do this by referring to an image like this: . ...

The alignment of vertical text can impact the positioning of surrounding text

I am working on creating an online portfolio using HTML and CSS, but I am facing a challenge with vertical alignment. My goal is to have a line of vertical text running down the left side of the screen that displays "My occupation". On the right side of t ...

Create an endless loop of two distinct animations with animate.css

Lately, I've encountered an issue with animate.css while working on my latest project. What I'm aiming to achieve is to update a paragraph of text on my website every five to ten seconds using jQuery. However, I don't want the text to simpl ...

Is there a way to extract data from the Redux state in a React component?

Seeking assistance with making an API request from Redux, followed by saving the data in my React state (arrdata). Although the API call is successful, I am facing challenges updating the App.js state based on the Redux API call. Any suggestions or insig ...