modifying button depending on the state of bootstrap collapse

I'm currently utilizing Bootstrap in my project.

Here is the snippet of HTML code I have:

 <div class="row">
        <button id="dog-btn" data-toggle="collapse" data-target="#dog-section" onclick="petToggle()">Show Pet</button>
    </div>


    <div class="col-12 collapse" id="dog-section">

Furthermore, I have the following JS code:

function petToggle() {
          var dogDiv = document.getElementById("dog-section");
          var dogBtn = document.getElementById("dog-btn");
 
        }

On my website, the initial state of 'dog-section' can vary. Sometimes it's visible and sometimes it's hidden. I attempted to determine the initial state using :hidden and :visible with jQuery, but it didn't give me the desired result. I want the button to display 'Show Pet' if the 'dog-section' is hidden due to the Bootstrap dropdown, and 'Hide Pet' if it's visible.

If you have any insights or solutions, please share them. Thank you.

Answer №1

If the CSS is currently set to visible, use a conditional statement to change it to hidden.

Using jQuery:

Check with jQuery:

if(dogSection.css('visibility') === 'hidden'){
  // make it visible
}else{
  // hide it
}

To set it to visible:

dogSection.css('visibility', 'visible')

To set it to hidden:

dogSection.css('visibility', 'hidden')

const $btn = $('#dog-btn')
const $dogSection = $('#dog-section')

function petToggle(){
  $btn.click(function(){
    if($dogSection.css('visibility') === 'hidden'){
      $dogSection.css('visibility', 'visible')
      $btn.text("Hide Pet Section")
    }else{
      $dogSection.css('visibility', 'hidden')
      $btn.text("Show Pet Section")
    }
  })
}

petToggle()
#dog-section {
  visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <button id="dog-btn" data-toggle="collapse" data-target="#dog-section">Show Pet Section</button>
</div>


<div class="col-12 collapse" id="dog-section">
   <img src="https://www.petmd.com/sites/default/files/sleeping-dogs-curled-up.jpg" alt="Sleeping Dog" width="450" height="355"> 
  <img href="">
</div>

Using vanilla Javascript...

Depending on how you are displaying your #dog-section in the DOM you can use one of the following.

if(getComputedStyle(dogSection).getPropertyValue('visibility') === 'hidden')
if(getComputedStyle(dogSection).getPropertyValue('display') === 'none')
if(dogSection.style.visibility === 'hidden';
if(dogSection.style.display === 'none';

Then set it using one of the following:

dogSection.style.setProperty('visibility', 'visible')
dogSection.style.visibility = 'visible'

const btn = document.getElementById('dog-btn')
const dogSection = document.getElementById('dog-section')

function petToggle(){
  btn.addEventListener('click', function(){
    if(getComputedStyle(dogSection).getPropertyValue('visibility') === 'hidden'){
      dogSection.style.setProperty('visibility', 'visible')
      btn.textContent = "Hide Pet Section"
    }else{
      dogSection.style.setProperty('visibility', 'hidden')
      btn.textContent = "Show Pet Section"
    }
  })
}

petToggle()
#dog-section {
  visibility: hidden;
}
<div class="row">
  <button id="dog-btn" data-toggle="collapse" data-target="#dog-section">Show Pet Section</button>
</div>


<div class="col-12 collapse" id="dog-section">
   <img src="https://www.petmd.com/sites/default/files/sleeping-dogs-curled-up.jpg" alt="Sleeping Dog" width="450" height="355"> 
  <img href="">
</div>

Answer №2

Eliminate the petToggle function. Utilize the collapse events to achieve your goal. Refer to the documentation for more information.

Considering that the dog-section may be hidden or shown initially, you should inspect the display style of the section and update the button text accordingly.

// Check the initial display state of the dog-section
// If it's hidden, set the button text to "Show Pet"
// If it's shown, set the button text to "Hide Pet"
if ($("#dog-section").css("display") === "none") {
    $("#dog-btn").text("Show Pet");
} else {
    $("#dog-btn").text("Hide Pet");
}

// Set the button text to "Hide Pet" when dog-section is shown
$("#dog-section").on("show.bs.collapse", function () {
    $("#dog-btn").text("Hide Pet");
});

// Set the button text to "Show Pet" when dog-section is hidden
$("#dog-section").on("hide.bs.collapse", function () {
    $("#dog-btn").text("Show Pet");
});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c6cbcbd0d7d0d6c5d4e4908a928a94">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1838e8e959295938091a1d5cfd7cfd1">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>

<div class="container">
    <div class="row">
        <button id="dog-btn" data-toggle="collapse" data-target="#dog-section">Show Pet</button>
    </div>

    <div class="row">
        <div class="col-12 collapse" id="dog-section">
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam quia suscipit amet ex aut. Odit error dolorem tempore, officiis sed, fugit in voluptate laboriosam quas illo ipsa alias magnam! Odit.
        </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

React native and redux: Updating state with setState is not possible during an ongoing state transition

Currently in the process of developing an app utilizing React Native and redux, alongside Express js for handling Ajax requests. Encountering an issue where the data from my Ajax request fails to load, accompanied by the following warning: Warning: set ...

Tips for lining up segmented pictures in HTML?

Recently, I was presented with a set of sliced images to insert into an HTML document. These images were not sliced by me, but rather provided as individual pieces. To showcase these images in a grid-like manner, I opted to construct a table layout. Each r ...

Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. ...

While validating in my Angular application, I encountered an error stating that no index signature with a parameter of type 'string' was found on type 'AbstractControl[]'

While trying to validate my Angular application, I encountered the following error: src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used ...

Transitioning from feelings to sewing: incorporate a duo of properties within variations and breakpoints

I was thinking about how to convert this styled-emotion code into stitches. Essentially, I need to handle the onlyShowOnDesktop and breakpoint props. The definition of breakpoint is as follows: const breakpoint = isTopNavigationBreakPoint ? theme.defaultB ...

The dropdown feature in AngularJS experiencing sporadic malfunctions on Google Chrome

HTML: <select id="bId" ng-options="b as b.name for b in books" ng-model="selectedBook" ng-change='onBookChange()'> </select> The issue: The options are not always displaying and the selected option is not visible. List ...

Once the database fetches and displays 500 results, the HTML/CSS formatting begins to

On my local webserver, I have a page running off SQLite as its database. Since it is used locally and loads results quickly, displaying all of them on one page isn't a concern. However, I'm facing an issue where the formatting goes awry after 500 ...

Prevent clicking here

I'm attempting to only prevent the click event on the current item with a certain class. $(document).on('click', '.item', function() { $(".item").removeClass('is-expanded'); $(this).addClass('is-expanded'); ...

Guide on creating a JSONP request

My goal is to perform cross-site scripting. The code snippet below shows the jsonp method, which appears to fail initially but succeeds when switched to a get request. I am trying to achieve a successful response using the jsonp method. I have confirmed th ...

Step-by-step guide on creating a clickable button that triggers the appearance of a block showcasing a dimmed photo upon activation

Is there a way to create a button that triggers a pop-up block featuring a darkened photo when clicked? ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Showing a series of text entries one after the other, each appearing with a smooth fade-in and fade-out

I am eager to showcase a list of text in a sequential order, implementing a fade-in/fade-out effect and concluding with the display of an image. Additionally, I aim to have all the text centered on the page. <div>a<div> <div>b</div> ...

Iterate through each image within a specific div element and showcase the images with a blur effect applied

I have a div with multiple images like this: <div class="am-container" id="am-container"> <a href="#"><img src="images/1.jpg"></img></a> <a href="#"><img src="images/2.jpg"></img>< ...

When a sidebar is added, Bootstrap 5 cards that are supposed to be displayed in a row end up being shown in a column instead

When I have a row of Bootstrap 5 cards that display correctly, but then add a sidebar that causes them to stack in a column instead of remaining in a row. How can I maintain the row layout even with the addition of a sidebar using specific CSS classes or p ...

The border-color feature in Bootstrap 5 does not function properly when applying responsive border-start/end/top/bottom styles

My Objective: For mobile: I want to have borders only at the top and bottom. For desktop: I want borders only at the start and end, in a border-dark color. My Attempts: I have added custom responsive borders to my main.scss file // responsive borders @ ...

Update PHP version by utilizing a form with varying field lengths

I am in the process of developing a feature on my website that will enable the admin to update player stats for the current season using a simple HTML form. However, I am facing some challenges in optimizing and making the script more efficient. To popula ...

The pdf2json encountered an error when attempting to process a PDF file sent via an HTTP

I am encountering an issue while attempting to extract information from PDF files using a nodejs script. Upon running the program, I encounter the following error: Error: stream must have data at error (eval at <anonymous> (/Users/.../node_modules/ ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

What is the procedure to alter the color of XYChart in JavaFx?

How can I change the color of a bar chart? Does anyone have any tips on: How to adjust the color of line charts? How to assign a CSS class to series? public class CustomBarChart extends Application { @Override public void start(Stage stage) throws Ex ...

What is the best way to set the active class on the initial tab that is determined dynamically rather than a static tab in Angular?

I'm currently facing a problem with ui-bootstrap's tabsets. I have one tab that is static (Other) and the rest are dynamically added using ng-repeat. The issue I'm having is that I can't seem to make the first dynamically loaded tab act ...