anad2312
anad2312

Reputation: 787

How to change CSS Bootstrap style using JavaScript dynamically?

I have this style in my custom css stylesheet:

.nav.nav-tabs > li > a {
    background-color: #c6dfff;
    margin-right: 5px;
    padding-left: 20px;
    padding-right: 20px;
    cursor: pointer;
    color: black;
}

I have a button using AngularJS ng-click:

<button type="button" class="btn btn-primary" ng-click="changeColor()">Change Color</button>

When the user clicks on the button, it calls a changeColor method:

            $scope.changeColor= function () {
                // Change Color Here
            }; 

I want to dynamically change the background-color of the above listed style to a different color.

Upvotes: 1

Views: 7413

Answers (2)

Samurai
Samurai

Reputation: 3754

Get the selected value from dropdown, either by using onchange on the select or in a button click. Then use the value to assign it to the background of the element you want.

HTML:

<select id="bgselect" onchange="changeBg()">
    <option value="black">Black</option>
    <option value="blue">Blue</option>
    <option value="#000080">Navy Blue</option>
    ...
</select>

Javascript:

function changeBg() {
    var bg = document.getElementById("bgselect").value;
    document.getElementById("dbg").style.background = bg;
}

jsfiddle DEMO

EDIT:

If you wanna affect elements like .nav.nav-tabs > li > a then you need to find all such elements and then apply the style:

function changeBg() {
    var bg = document.getElementById("bgselect").value;
    var navs = document.querySelectorAll(".nav.nav-tabs");
    var as = navs[0].getElementsByTagName('a');
    for(var i = 0; i < as.length; i++) {
        as[i].style.background = bg;
    }
}

updated jsfiddle

Upvotes: 0

user4826496
user4826496

Reputation:

alright, so If you want to use javascript, you could do this one of two ways. The first would be to assign the object an ID, or if multiple objects you would use a class.

for an ID

document.getElementById("myId").style.backgroundColor="yourcolor"

replace your color with the color you want and myID with the ID of the object. If you have multiple objects with the same class,

for a class

document.getElementsByClassName("myclassname").style.backgroundColor="yourcolor"

again, replace the myclassname with the name of the class; same for your color

or if you want to use JQuery

$(".myclassname").css("background-color", "your color");

typically, you use classes for multiple items, and IDs for single ones. feel free to comment and Ill add anything else you need; as i am a little uncertain of the specifics of what you are asking.

Upvotes: 2

Related Questions