I have more than one button and I have a class named bg. In the CSS file, I styled this bg class, but at the same time, I want to be able to change its colors dynamically from the JS file. the background is only one color, but I can make different colors that I want, for example, color codes are coming from the API (red for test1, yellow for test2, etc.). I want to use whatever code comes up. For example, going to the test2 page, then the background is yellow. I can do this by creating classes as test1 and test2 in the css file, but it is not useful because there may be hundreds of pages, it is much more logical to use the color code from the API instead of the troubles of adding them one by one to the css file.
$('.bg').click(function(){
$(this).unbind('mouseenter mouseleave');
$('.bg').removeClass('active');
$('.bg.active').css('background','yellow');
$(this).addClass('active');
}).hover(
function(){
$(this).css({
'border-color': '#4000a1',
'background': 'blue'
});
},
function(){
$(this).css({
'border-color': '#4000a1',
'background': 'transparent'
});
});
.bg{
border: 2px solid #4000a1;
background: gray;
width: 200px;
height: 150px;
margin-bottom: 20px;
}
.bg.active{
background: red;
}
.bg:hover{
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='bg'></div>
<div class='bg'></div>
I tried something like this but it seems hover works properly but when clicked it stays fixed but I want only one of them to stay active. Also in my original file addClass and removeClass are done in another file and properly there is only one active class but the style does not change.
I hope I can explain my problem properly.