psylosss
psylosss

Reputation: 3529

How can I hide an 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?

Upvotes: 265

Views: 412938

Answers (22)

Neil Meyer
Neil Meyer

Reputation: 591

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 */
<a href="#">This will disappear when it is clicked.</a>

Example with button

#btn-01:active ~ p {
            display: none;
         }
<button id="btn-01"> click me</button>
<p id="text">Some Example Text</p>

Upvotes: 0

Hossein
Hossein

Reputation: 3107

In Bootstrap 4 you can use the d-none class to hide an element completely.

Display property

Upvotes: 2

Selay
Selay

Reputation: 6464

Hide and hidden are both deprecated and later removed, and they 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 the visibility and display utilities:

Visibility

Display property

Upvotes: 1

Sagar Gala
Sagar Gala

Reputation: 944

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().

    /*
     * .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;
    };

Upvotes: 0

Iv&#225;n
Iv&#225;n

Reputation: 391

Use Bootstrap's .collapse instead of .hidden.

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

Upvotes: 29

Th&#233;o T. Carranza
Th&#233;o T. Carranza

Reputation: 8449

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.

Upvotes: 6

evalarezo
evalarezo

Reputation: 1153

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

Upvotes: 0

Evan Carroll
Evan Carroll

Reputation: 1

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;
}

Upvotes: 450

Ricky Levi
Ricky Levi

Reputation: 7997

I solved my issue by editing the Bootstrap CSS file. See their documentation:

.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 :)

Upvotes: -1

user2312234
user2312234

Reputation: 265

Bootstrap provides classes for toggling content. See bootstrap/less/utilities.less.

I'm completely new to jQuery, and after reading their documentation I came to another solution to combine 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 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 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 Bootstrap, which is optimized for [assistive technology][3] as well (screen readers). So, if we want to show the hidden div, we need to get rid of the .hidden class of 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 use .toggleClass 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 Bootstrap 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" );
    });
});

Upvotes: -2

Andres Separ
Andres Separ

Reputation: 3394

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();
});

Upvotes: 3

Ray C Lin
Ray C Lin

Reputation: 703

$(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.

Upvotes: 2

William Entriken
William Entriken

Reputation: 39263

โ˜€๏ธ 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();
}

Upvotes: 4

isteeak
isteeak

Reputation: 21

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 ));
  1. Put the above code in a file. Let's suppose "myJqExt.js"
  2. Include the file after jQuery has been included.

  3. Use it using the syntax

    $().hideShow('hide');

    $().hideShow('show');

hope you guys find it helpful. :-)

Upvotes: 2

Chloe
Chloe

Reputation: 26264

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.

<input type="text" hidden>

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.

Upvotes: 2

Dustin Graham
Dustin Graham

Reputation: 2086

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.

Upvotes: 18

badboy
badboy

Reputation: 106

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.

Upvotes: 2

MichaelJTaylor
MichaelJTaylor

Reputation: 344

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.

Upvotes: 5

JacksonT
JacksonT

Reputation: 63

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...

Upvotes: 2

dbrin
dbrin

Reputation: 15673

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();

Upvotes: 14

AndreDurao
AndreDurao

Reputation: 5795

I like to use the toggleClass:

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

Upvotes: 2

Razz
Razz

Reputation: 4005

Simply:

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

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

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

Upvotes: 66

Related Questions