Bryan
Bryan

Reputation: 3541

Change background on li element on click

The thing I want to do is when a user clicks on a link, the background should change to Indicate which Link the user has clicked on. I'm trying to do this with jQuery:

$('.menuLink').click(function() {
  var img = $(this).find('img');
  var id = $(this).attr('id');
  $("#" + id).addClass('activeLink');
  console.log(id);
});
.menuLinks li {
  color: #ffffff;
  float: left;
  margin-left: 2px;
  width: 115px;
  height: 60px;
  background-color: #004f80;
  text-align: center;
  font-size: 13px;
  font-weight: normal;
  font-style: normal;
  font-stretch: normal;
}
.menuLinks li:hover {
  background-color: #006eb3;
  cursor: pointer;
}
.menuLinks li a {
  color: #fff;
}
.activeLink {
  color: #004f80;
  background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menuLinks">
  <li class="menuLink" id="tillstandshavare">Link1</li>
  <li class="menuLink" id="stationer">Lnk2</li>
  <li class="menuLink" id="formular">Link3</li>
  <li class="menuLink" id="fragor">Link4</li>
  <li class="menuLink" id="installningar">Link5</li>
</ul>

As you can see, I'm attaching the activeLink class. But the background are never changed. I think this is because of menuLinks is not overrided.

Upvotes: 2

Views: 1947

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because the .activeLink class is not specific enough for it to override the default .menuLink li styling. You need to make it more specific. Also note that you can use this to reference the clicked element instead of building the id selector string manually. Try this:

$('.menuLink').click(function() {
  $(this).addClass('activeLink');
});
.menuLinks li {
  color: #ffffff;
  float: left;
  margin-left: 2px;
  width: 115px;
  height: 60px;
  background-color: #004f80;
  text-align: center;
  font-size: 13px;
  font-weight: normal;
  font-style: normal;
  font-stretch: normal;
}
.menuLinks li:hover {
  background-color: #006eb3;
  cursor: pointer;
}
.menuLinks li a {
  color: #fff;
}
.menuLinks li.activeLink {
  color: #004f80;
  background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menuLinks">
  <li class="menuLink" id="tillstandshavare">Link1</li>
  <li class="menuLink" id="stationer">Lnk2</li>
  <li class="menuLink" id="formular">Link3</li>
  <li class="menuLink" id="fragor">Link4</li>
  <li class="menuLink" id="installningar">Link5</li>
</ul>

Upvotes: 2

Related Questions