R Gao
R Gao

Reputation: 19

How do I change the drop down button color when clicked Bootstrap?

I installed this Bootstrap drop down button https://getbootstrap.com/docs/4.0/components/dropdowns/ (the second one with the "a" element, so my "button" is really a link) and everything works perfectly, except when I try to change the background color of the button when it is clicked; it remains the default grey that comes with the button as well as the light grey border that appears. I want to change the background color when the button is clicked.

Here is my code:

(Just to`explain, my html is in li because I use the drop down button as a menu item for the navigation, and I am using span instead of div because it will only align properly with span instead of forming a block.)

html:

<span class="dropdown show">

    <li>

        <a class="btn btn-secondary dropdown-toggle" href="#" role="button" 
        id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" 
        aria-expanded="false" onclick="myFunction()">Help</a>

    <span class="dropdown-menu" aria-labelledby="dropdownMenuLink">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action</a>
        <a class="dropdown-item" href="#">Something else here</a>
    </span>
    </li>
</span>

CSS:

    #color-change {
    background-color: #00ffba;
}

Javascript:

    function myFunction() {
    document.getElementById("color-change");
} 

I've looked online and tried other ways of changing the background color when clicking, but to no avail, I reckon it might be something to do with the list element and/or span element interfering with the Javascript, along with interfering with Bootstrap, but my Javascript is also likely wrong.

Thanks!

`

Upvotes: 0

Views: 6751

Answers (2)

Sajan Lamsal
Sajan Lamsal

Reputation: 317

You can achieve this via simple CSS. Add one class in the tag.

 <a class="btn btn-secondary dropdown-toggle customButton" href="#" role="button"
       id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true"
       aria-expanded="false">Help</a>

CSS

.show > .customButton:focus{
background: #00ffba !important ;
  box-shadow:none !important;
  border: none !important;

}
.customButton{
  box-shadow:none !important;
  border: none !important;
}

If you want all your btn-secondary to be same color when clicked then you can add the css directly to that class as follows:

.show > .btn-secondary:focus{
background: #00ffba !important ;
  box-shadow:none !important;
  border: none !important;

}
.btn-secondary{
  box-shadow:none !important;
  border: none !important;
}

Codepen link :https://codepen.io/anon/pen/xzWrYr

Upvotes: 5

rameezmeans
rameezmeans

Reputation: 850

this code will work for you. change ID and colour for you.

$('body').on('click', '#id-of-button-to-change-background', function(){

    $(this).css('background-color', 'colour-to-change-will-go-here');

})

Upvotes: 0

Related Questions