conceal and reveal a hidden div using a button

I am having an issue with my jQuery code. I have a button and a div element. The button should toggle the visibility of the div when clicked. I tried using a test to check the class of the div element. If the div is hidden, I want to make it visible, and if it's visible, I want to hide it. Here is the code I have, but I can't figure out what is wrong:

<button type="button" class="btn btn-default" id="btn-collapse">Left</button>
<div id="mapBlock" class="hidden"></div>

<script type="text/javascript">
$(document).ready(function() {
  var classe = $('#mapBlock').attr('class');
  
  $('#btn-collapse').click(function() {
    if(classe == "hidden") {
      $('#mapBlock').removeClass("hidden").addClass("visible");  
    }
    if(classe == "visible") {
      $('#mapBlock').removeClass("visible").addClass("hidden");  
    }
  });
});
</script>

Answer №1

Make sure to click on the button whenever you attend the class

$('#btn-collapse').click(function() {
    var classValue = $('#mapBlock').attr('class');
    if (classValue == "hidden") {
        $('#mapBlock').removeClass("hidden").addClass("visible");
    }
    if (classValue == "visible") {
        $('#mapBlock').removeClass("visible").addClass("hidden");
    }
});

Consider using .hasClass() for better results

 $('#btn-collapse').click(function() {

        if ($('#mapBlock').hasClass("hidden")) {
            $('#mapBlock').removeClass("hidden").addClass("visible");
        }
        if ($('#mapBlock').hasClass("visible")) {
            $('#mapBlock').removeClass("visible").addClass("hidden");
        }
    });

Answer №2

Is there a reason for not simply using toggle() to toggle the visibility?

$('#btn-collapse').on('click', function() {
    $('#mapBlock').toggle(); 
});

Answer №3

If you're looking for a simple solution, you might want to consider using the toggleClass method. This method doesn't require you to have any understanding of the current state of the object, and it simply toggles between two states:

$('#toggle-button').click(function() {
    $('#content-block').toggleClass("is-hidden");
});

Answer №4

When the document is ready, the class attributes of #mapBlock are stored in the variable 'classe'.

Therefore, when you click the button, your if statements will always be compared to what was saved initially, without updating each time. To make it work, try declaring the variable inside your function.

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

Steps to create a loading bar that starts loading when an ajax task begins

What is the best way to show a loading bar as an AJAX task begins on a page? Additionally, how can we make sure that hitting the back button will return to what was being viewed before that specific AJAX task? ...

The challenge of overlapping elements in jQuery UI resizable

Encountering an issue with the resizable class in jQuery UI (http://jqueryui.com/resizable/). When resizing begins, all divs below move to overlap with the resizing div. Upon inspecting the js console in chrome, it appears that resizable applies inline sty ...

Bookmarklet in JavaScript that automatically extracts and displays Meta keywords in a new tab within the browser

I successfully implemented a script that extracts site meta keywords and writes them into the DOM. javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i=0;i<metaCollection.length;i++) { nameAttri ...

Image source not functioning properly

I am attempting to dynamically load an image and HTML using Angular but it doesn't seem to be working. Here is what I have tried: <img ng-src="img/{{product.Category}}/{{product.id}}.jpg"> and also this: <img src="img/{{product.Category}}/ ...

Adjusting Image Width with jQuery on Hover

I am trying to create a hover effect for two images placed side by side. When the user hovers over one of the images, it should expand. HTML: <a href="#"><div id="skinny"></div></a> <a href="#"><div id="room9"></div ...

Addressing the Summer Note Problem within a Bootstrap Popup

I am currently facing an issue with the functionality of the Summernote Text plugin in my project. The text inside the Summernote editor does not display what I am typing until I resize the browser window. Below is the code snippet for reference: <%-- ...

Formula for full width skew in three adjacent divs using SkewX() function

.container { height: 500px; width: 500px; position: relative; background: black; } .box { transform: skewX(20deg); width: 33%; height: 100%; position: absolute; } .first-box { background: purple; left: 0; } .second-box { background ...

Analyzing JSON parsing efficiency

I am currently working on a client application using jquery and html5 For my project, I have a data file that is 70 MB in size The file named data.json contains the following: var myData = [ { "id":"000000001", "title":"title1", "c ...

Dealing with blank values in jQuery DataTables

I am currently utilizing jQuery DataTable to display data in table format; within the table, there is a button that triggers a Bootstrap Modal for editing two of these values, and I utilize Ajax to send the modified values to a Spring Controller. The init ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

Embed jQuery in the Meteor server-side code

During my search, I came across the following links: https://groups.google.com/forum/#!topic/meteor-core/ZlPPrH7SqrE Server-side jquery How can one parse HTML server-side with Meteor? Despite my efforts, I have not yet found a way to incorporate jQuery ...

Is there a way to divide text in half while preserving the HTML structure?

I am in need of setting up an RSS feed where only a portion (or a specified number of characters) of the article's text is displayed, while keeping all HTML tags intact (such as images or YouTube videos). For instance, what should happen if the chara ...

Can I create a div with a rounded right side?

Is there a way to give a div a slightly rounded right side using CSS? If so, can you show me how in this fiddle template: http://jsfiddle.net/z2hejemu/ HTML <div class="rounded-side"> <p>By default, this div is rectangular. I would like t ...

Arrange three input fields horizontally with labels positioned above each

I am facing a minor problem with aligning three input fields in the same row while maintaining equal spacing between each of them. I attempted to accomplish this using display: flex and space-between, but then the label appears to the left of the input in ...

Explaining the functionality of JsHelper Request success/error/complete callbacks in CakePHP version 2.1

I am currently in the process of creating a request page for invitations using CakePHP 2.1 framework, jQuery, and Cake's JsHelper to handle the submission of user emails and provide a response. My goal is to have the form fade out only after the email ...

Recursive instruction malfunctioning

I'm currently trying to develop a custom recursion directive, but unfortunately it's not functioning as expected. I have followed the instructions outlined here: Recursion in Angular directives For reference, you can view the fiddle here: http ...

Passing form values from JavaScript to a JSP page - a comprehensive guide

I am working on a sample HTML page that includes inline JavaScript for calculating geocodes and retrieving latitude and longitude values. My question is, how can I submit all the form values along with the latitude and longitude returned from the showlocat ...

Calculating the percentage in a jQuery Slider

For a while now, I've been using var slideWidth = 420; to set the width of sliders and then $('#slideInner').css('width', slideWidth * numberOfSlides); to calculate the total width of all sliders effectively in pixels. An Issue Ar ...

Organize results from MySql using php

Trying to retrieve table values from a MySQL database sorted has proven to be a challenge for me. While I am able to connect and update the table successfully, I struggle with displaying the messages in the HTML chat history sorted by time. Is there a mo ...

How to Retrieve URL Before Closing a jQuery Window Using window.open()?

Is it feasible to retrieve the URL of a window.open window after triggering a window.close event when the user clicks the close button? How can I obtain the last URL visited right before the window closes? ...