4

I want to change the background color when the li anchors are clicked:

<div class="text-center row">
  <ul  class="col-md-12 secondNav">
    <li class="navbar-brand nav-item" style="margin-right: 9%">
      <a href="#" ><strong>INICIO</strong> </a>
    </li>
    <li  class="navbar-brand nav-item" >
      <a href="#"><strong>COMPARAR</strong></a>
    </li>
  </ul>
</div>
Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
harry
  • 53
  • 1
  • 5
  • Possible duplicate of [Change background on li element on click](https://stackoverflow.com/questions/39505578/change-background-on-li-element-on-click) – Nick Apr 11 '19 at 00:27

4 Answers4

2

You can use jquery to change the li background. Here is the code:

$(document).ready(function(){
  $('.nav-item').click(function(e){
  $(e.target).css('backgroundColor', 'red');
   });
});

jsfiddle

pmarre
  • 93
  • 1
  • 9
1

So, while I don't necessarily recommend this solution. It is actually possible to do this without javascript! Check out this example: https://jsfiddle.net/age5zdkb/2/

<div class="text-center row">
  <ul  class="col-md-12 secondNav">
    <a href="#" >
      <li class="navbar-brand nav-item" style="margin-right: 9%">
        <input type="checkbox" id="demo"/>
        <label for="demo"><strong>INICIO</strong></label>
      </li>
    </a>
    <a href="#" >
      <li  class="navbar-brand nav-item" >
        <input type="checkbox" id="demo1"/>
        <label for="demo1"><strong>COMPARAR</strong></label>
      </li>
    </a>
  </ul>
</div>

label {
    display: block;
}

input[type="checkbox"] {
  display:none;
}

#demo:checked + label, #demo1:checked + label {
    background: pink;
    color: white;
}
JoRoFo
  • 71
  • 5
0

Here's how you can do it without any dependencies.

const listItems = document.querySelectorAll('.navbar-brand');

listItems.forEach(li => {
  li.addEventListener('click', () => {
    li.classList.toggle('alt-background');
  });
});
.alt-background {
  background-color: lightgray;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="text-center row">
  <ul  class="col-md-12 secondNav">
    <li class="navbar-brand nav-item" style="margin-right: 9%">
      <a href="#" ><strong>INICIO</strong> </a>
    </li>
    <li  class="navbar-brand nav-item" >
      <a href="#"><strong>COMPARAR</strong></a>
    </li>
  </ul>
</div>

jsFiddle

Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
0

You can use jquery to add active class when you click a nav-item in css add background color for active item

https://jsfiddle.net/binoy/g6e1bykx/3/

In JS

   $(document).ready(function(){
            $('.nav-item').click(function(e){
                $('.secondNav .nav-item').removeClass('active');
                $(this).addClass('active');
             });
    });



In  CSS
.secondNav .nav-item.active {
  background-color: red;
}