search

Home  >  Q&A  >  body text

Dynamically change static colors in css file using jquery

I have multiple buttons and I have a class called bg. In the CSS file, I style the bg class, but at the same time, I want to be able to dynamically change its color from the JS file. The background is only one color, but I can make different colors I want, for example, the color codes come from the API (red for test1, yellow for test2, etc.). I want to use whatever code comes up. For example, if you go to the test2 page, the background will be yellow. I could do it by creating classes test1 and test2 in the css file but it doesn't work as there could be hundreds of pages and it would be more logical to use the color codes from the API than the hassle of adding them 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 similar but it seems the hover works fine but when clicked it stays fixed but I only want one of them to stay active. Also, in my original file, addClass and removeClass are done in another file, and correctly there is only one active class, but the style does not change.

I hope I explained my problem correctly.

P粉459440991P粉459440991254 days ago339

reply all(1)I'll reply

  • P粉684720851

    P粉6847208512024-03-20 19:58:00

    I'm not sure the exact result you want, but I made some changes to your code so there is only one active background at a time. I also simplified. You're hovering over CSS, you're hovering over JavaScript... for something simple, go ahead and hover over the CSS file. Use JavaScript to handle click events.

    $('.bg').click(function(){
      $('.bg').css({backgroundColor: ''});
      $(this).css({backgroundColor: $(this).data('color')});
    })
    .bg{
      border: 2px solid #4000a1;
      background: gray;
      width: 200px;
      height: 150px;
      margin-bottom: 20px;
    }
    
    .bg:hover{
      background: red;
    }
    
    

    reply
    0
  • Cancelreply