ChatGPT解决这个技术问题 Extra ChatGPT

How to hide element using Twitter Bootstrap and show it using jQuery?

Let's say I create an HTML element like this,

<div id="my-div" class="hidden">Hello, TB3</div>
<div id="my-div" class="hide">Hello, TB4</div>
<div id="my-div" class="d-none">Hello, TB4</div>

How could I show and hide that HTML element from jQuery/Javascript.

JavaScript:

$(function(){
  $("#my-div").show();
});

Result: (with any of these).

I would like the elements above to be hidden.

What is simplest way to hide element using Bootstrap and show it using jQuery?

In order to keep this question relevant, I've modified it to work on both Bootstraps, because the answer is only a difference in class name.

F
FlipperPA

The right answer

Bootstrap 4.x

Bootstrap 4.x uses the new .d-none class. Instead of using either .hidden, or .hide if you're using Bootstrap 4.x use .d-none.

<div id="myId" class="d-none">Foobar</div>

To show it: $("#myId").removeClass('d-none');

To hide it: $("#myId").addClass('d-none');

To toggle it: $("#myId").toggleClass('d-none');

(thanks to the comment by Fangming)

Bootstrap 3.x

First, don't use .hide! Use .hidden. As others have said, .hide is deprecated,

.hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1

Second, use jQuery's .toggleClass(), .addClass() and .removeClass()

<div id="myId" class="hidden">Foobar</div>

To show it: $("#myId").removeClass('hidden');

To hide it: $("#myId").addClass('hidden');

To toggle it: $("#myId").toggleClass('hidden');

Don't use the css class .show, it has a very small use case. The definitions of show, hidden and invisible are in the docs.

// Classes
.show {
  display: block !important;
}
.hidden {
  display: none !important;
  visibility: hidden !important;
}
.invisible {
  visibility: hidden;
}

Thank you so much I was wondering stackoverflow for something like this for long time for simple answer. Thank you
Anyone has an idea what are the methods: show() and hide() for then?
Then you can't animate it (eg. fadeIn()). Therefore use the class collapse instead of hidden. And then of course there is no need for using removeClass, addClass, etc.
For Bootstrap 4 you have to use .hidden-xs-up. v4-alpha.getbootstrap.com/layout/responsive-utilities/… There is also hidden HTML5 attribute. v4-alpha.getbootstrap.com/content/reboot/…
@Kangur jQuery .hide() isn't bootstrap's .hide class. The jQuery method works fine, but it's not the bootstrap way. Bootstrap libraries depend on the inclusion of the .hidden class on the element to determine it's not there. jQuery doesn't add that -- unless you hack it like here: stackoverflow.com/a/27439371/124486, in which case you could break other jQuery specific things.
R
Razz

Simply:

$(function(){
  $("#my-div").removeClass('hide');
});

Or if you somehow want the class to still be there:

$(function(){
  $("#my-div").css('display', 'block !important');
});

Here's a jQuery plugin that allows you to use .show() and .hide() even with the bootstrap 'hidden' and 'hide' classes. gist.github.com/zimkies/8360181
According to Bootstrap documentation, .hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1. Use .hidden or .sr-only instead.
I
Iván

Use bootstrap .collapse instead of .hidden

Later in JQuery you can use .show() or .hide() to manipulate it


D
Dustin Graham

This solution is deprecated. Use the top voted solution.

The hide class is useful to keep the content hidden on page load.

My solution to this is during initialization, switch to jquery's hide:

$('.targets').hide().removeClass('hide');

Then show() and hide() should function as normal.


.hide is deprecated as of v3.0.1
Ok, use .hidden as of v3.0.1
In this case, there might be flickers of content that is shown for microseconds before hidden with JS.
Calling .hide() first applies display:none; to the style tag. This happens prior to removing the hide class. If you have it in that order, it shouldn't flicker.
d
dbrin

Another way to address this annoyance is to create your own CSS class that does not set the !important at the end of rule, like this:

.hideMe {
    display: none;
}

and used like so :

<div id="header-mask" class="hideMe"></div>

and now jQuery hiding works

$('#header-mask').show();

It circumvents the problem posed by using bootstrap's classes. Why downvote this short and simple solution?
Because this short and simple solution doesn't answer the question which specifically calls for the use of bootstrap3's classes. Not to mention, while simple, .hidden in Bootstrap is defined as .hidden { display: none !important; visibility: hidden !important; }
and that is exactly the problem, JQuery hide and show methods do not work well with this css.
M
MichaelJTaylor

The method @dustin-graham outlined is how I do it too. Remember also that bootstrap 3 now uses "hidden" instead of "hide" as per their documentation at getbootstrap. So I would do something like this:

$(document).ready(function() {
    $('.hide').hide().removeClass('hide');
    $('.hidden').hide().removeClass('hidden');
});

Then whenever using the jQuery show() and hide() methods, there will be no conflict.


So elegant and simple -- you just overcame a common Bootstrap deficiency. I would use hidden class and then try to do show() in jQuery, and nothing would happen. Your solution fixes this so easily, and I didn't think of it.
T
Théo T. Carranza

Initiate the element with as such:

<div id='foo' style="display: none"></div>

And then, use the event you want to show it, as such:

$('#foo').show();

The simplest way to go I believe.


A
Andres Separ

HTML:

<div id="my-div" class="hide">Hello, TB3</div>

Javascript:

$(function(){
    //If the HIDE class exists then remove it, But first hide DIV
    if ( $("#my-div").hasClass( 'hide' ) ) $("#my-div").hide().removeClass('hide');

    //Now, you can use any of these functions to display
    $("#my-div").show();
    //$("#my-div").fadeIn();
    //$("#my-div").toggle();
});

A
AndreDurao

I like to use the toggleClass:

var switch = true; //it can be an JSON value ...
$("#my-div").toggleClass('hide', switch);

This would be great, but the switch is entirely not needed.
R
Ray C Lin
$(function(){

$("#my-div").toggle();

$("#my-div").click(function(){$("#my-div").toggle()})

})

// you don't even have to set the #my-div .hide nor !important, just paste/repeat the toggle in the event function.


J
JacksonT

Recently ran into this when upgrading from 2.3 to 3.1; our jQuery animations (slideDown) broke because we were putting hide on the elements in the page template. We went the route of creating name-spaced versions of Bootstrap classes that now carry the ugly !important rule.

.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...

3.1 doesn't support .hide, it has .hidden.
b
badboy

Razz's answer is good if you're willing to rewrite what you have done.

Was in the same trouble and worked it out with the following:

/** * The problem: https://github.com/twbs/bootstrap/issues/9881 * * This script enhances jQuery's methods: show and hide dynamically. * If the element was hidden by bootstrap's css class 'hide', remove it first. * Do similar in overriding the method 'hide'. */ !function($) { "use strict"; var oldShowHide = {'show': $.fn.show, 'hide': $.fn.hide}; $.fn.extend({ show: function() { this.each(function(index) { var $element = $(this); if ($element.hasClass('hide')) { $element.removeClass('hide'); } }); return oldShowHide.show.call(this); }, hide: function() { this.each(function(index) { var $element = $(this); if ($element.hasClass('show')) { $element.removeClass('show'); } }); return oldShowHide.hide.call(this); } }); }(window.jQuery);

Throw it away when Bootstrap comes with a fix for this problem.


Is it necessary or optimal to check if the class exists before you call .removeClass() or .addClass()?
Also, doesn't .removeClass() already work over the set? Couldn't you simply call $(this).removeClass('show')
H
Hossein

In bootstrap 4 you can use d-none class to hide an element completely. https://getbootstrap.com/docs/4.0/utilities/display/


C
Community

Update: From now on, I use .collapse and $('.collapse').show().

For Bootstrap 4 Alpha 6

For Bootstrap 4 you have to use .hidden-xs-up.

https://v4-alpha.getbootstrap.com/layout/responsive-utilities/#available-classes

The .hidden-*-up classes hide the element when the viewport is at the given breakpoint or wider. For example, .hidden-md-up hides an element on medium, large, and extra-large viewports.

There is also hidden HTML5 attribute.

https://v4-alpha.getbootstrap.com/content/reboot/#html5-hidden-attribute

HTML5 adds a new global attribute named [hidden], which is styled as display: none by default. Borrowing an idea from PureCSS, we improve upon this default by making [hidden] { display: none !important; } to help prevent its display from getting accidentally overridden. While [hidden] isn’t natively supported by IE10, the explicit declaration in our CSS gets around that problem.

There is also .invisible which does affect the layout.

https://v4-alpha.getbootstrap.com/utilities/invisible-content/

The .invisible class can be used to toggle only the visibility of an element, meaning its display is not modified and the element can still affect the flow of the document.


i
isteeak

Use the following snippet for Bootstrap 4, which extends jQuery:

(function( $ ) {

    $.fn.hideShow = function( action ) {

        if ( action.toUpperCase() === "SHOW") {
            // show
            if(this.hasClass("d-none"))
            {
                this.removeClass("d-none");
            }

            this.addClass("d-block");

        }

        if ( action.toUpperCase() === "HIDE" ) {
            // hide
            if(this.hasClass("d-block"))
            {
                this.removeClass("d-block");
            }

            this.addClass("d-none");
      }

          return this;
    };

}( jQuery ));

Put the above code in a file. Let's suppose "myJqExt.js" Include the file after jQuery has been included. Use it using the syntax $().hideShow('hide'); $().hideShow('show');

hope you guys find it helpful. :-)


W
William Entriken

☀️ The righter answer

In Bootstrap 4 you hide the element:

<p id="insufficient-balance-warning" class="d-none alert alert-danger">Pay me</p>

🛑 Then, sure, you could literally show it with:

if (pizzaFundsAreLow) {
  $('#insufficient-balance-warning').removeClass('d-none');
}

💓 But if you do it the semantic way, by transferring responsibility from Bootstrap to jQuery, then you can use other jQuery niceties like fading:

if (pizzaFundsAreLow) {
  $('#insufficient-balance-warning').hide().removeClass('d-none').fadeIn();
}

S
Selay

hide and hidden are both deprecated and later removed, no longer exist in new versions. You can use d-none/d-sm-none/invisible etc classes depending on your needs. The probable reason they were removed is because hidden/hide is a bit confusing in the CSS context. In CSS, to hide (hidden) is used for visibility, not for display. visibility and display are different things.

If you need a class for visibility:hidden, then you need invisible class from visibility utilities.

Check below both visibility and display utilities:

https://getbootstrap.com/docs/4.1/utilities/visibility/

https://getbootstrap.com/docs/4.1/utilities/display/


e
evalarezo

Bootstrap, JQuery, namespaces... What is wrong with a simple:

var x = document.getElementById('my-div');
x.className.replace(/\bhide\b/, ''); //remove any hide class
x.style.display = ''; //show
x.style.display = 'none'; //hide

You can create a little helper function, KISS compliant:

function mydisplay(id, display) {
    var node = (typeof id == 'string') ? document.getElementById(id) : id;
    node.className.replace(/\bhide\b/, '');
    if (node) {
        if (typeof display == 'undefined') {
            display = (node.style.display != 'none');
        } else if (typeof display == 'string' && display == 'toggle') {
            display = mydisplay(node, !mydisplay(node));
        } else {
            node.style.display = (display) ? '' : 'none';
        }
    }
    return display;
}
is_hidden = mydisplay('my-div'); //actual state
mydisplay('my-div', false); //hide
mydisplay('my-div', true); //show
mydisplay('my-div', 'toggle'); //toggle state

S
Sagar Gala

Based on the above answers, I have just added my own functions and this further doesn't conflict with the available jquery functions like .hide(), .show(), .toggle(). Hope it helps.

    /*
     * .hideElement()
     * Hide the matched elements. 
     */
    $.fn.hideElement = function(){
        $(this).addClass('hidden');
        return this;
    };

    /*
     * .showElement()
     * Show the matched elements.
     */
    $.fn.showElement = function(){
        $(this).removeClass('hidden');
        return this;
    };

    /*
     * .toggleElement()
     * Toggle the matched elements.
     */
    $.fn.toggleElement = function(){
        $(this).toggleClass('hidden');
        return this;
    };

N
Neil Meyer

There is a solution without JQuery

You can use the CSS Pseudo class :Active to hide the element when clicked. This pseudo class is mainly used on anchor tags and buttons.

So for instance.

a:active { display: none; } /* Active links */ This will dissapear when it is clicked.

Example with button

#btn-01:active ~ p { display: none; }

Some Example Text


A
Andhi Irawan

I solved my issue by editing the Bootstrap CSS file, see their doc:

.hide:

.hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1

.hide {
  display: none !important;
}

.hidden is what we're suppose to use now, but it is actually:

.hidden {
  display: none !important;
  visibility: hidden !important;
}

The jQuery "fadeIn" won't work because of the "visibility".

So, for the latest Bootstrap, .hide is no longer in use, but it's still in the min.css file. so I left .hidden AS IS and just removed the "!important" from the ".hide" class ( which is supposed to be deprecated anyway ). but you can also just override it in your own CSS, I just wanted all my application to act the same so I changed the Bootstrap CSS file.

And now the jQuery "fadeIn()" works.

The reason that I've done this vs the suggestions above, is because when you "removeClass('.hide')" the object immediately is shown, and you skip the animation :)

I hope it helped others.


A
Andhi Irawan

Twitter Bootstrap provides classes for toggling content, see https://github.com/twbs/bootstrap/blob/3ee5542c990817324f0a07b97d01d1fe206fd8d6/less/utilities.less.

I'm completely new to jQuery, and after reading their docs I came to another solution to combine Twitter Bootstrap + jQuery.

First, the solution to 'hide' and 'show' an element (class wsis-collapse) when clicking on another element (class wsis-toggle), is to use .toggle.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle();
    });
});

You already have hidden the element .wsis-collapse by using Twitter Bootstrap (V3) class .hidden also:

.hidden {
  display: none !important;
  visibility: hidden !important;
}

When you click on .wsis-toggle, the jQuery is adding an inline style:

display: block

Because of the !important in the Twitter Bootstrap, this inline style has no effect, so we need to remove the .hidden class, but I won't recommend .removeClass for this! Because when jQuery is going to hide something again, it's also adding an inline style:

display: none

This is not the same as the .hidden class of Twitter Bootstrap, which is optimized for AT as well (screen readers). So, if we want to show the hidden div, we need to get rid of the .hidden class of Twitter Bootstrap, so we get rid of the important statements, but if we hide it again, we want to have the .hidden class back again! We can using [.toggleClass][3] for this.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle().toggleClass( "hidden" );
    });
});

This way you keep using the hidden class every time the content is hidden.

The .show class in TB is actually the same as the inline style of the jQuery, both 'display: block'. But if the .show class at some point will be different, then you simply add this class as well:

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle().toggleClass( "hidden show" );
    });
});

@EvanCarroll, why is it complex? I've been reading your answer as well and I see you suggest to use toggleClass which I also do, so I don't understand your comment.