0

I don't know if I am speaking correctly, because I am new to HTML. I have a ul menu with four boxes that are li's. I want a box to have a white border if I click that box.

This is my HTML code:

$("ul.quantity-grid li").click(function(){
    $(this).addClass("active").siblings().removeClass("active");
});
.quantity-grid li.active{
  border:4px solid #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="quantity-grid">
  <li class="1bag" data-value="1">
    <h3>1 BAG, $35</h3>
    <img src="img/1bag.png">
  </li>

  <li class="2bags" data-value="2">
    <h3>2 BAGS, $45</h3>
    <img src="img/2bags.png">
  </li>

  <li class="3bags" data-value="3">
    <h3>3 BAGS, $65</h3>
    <img src="img/3bags.png">
  </li>

  <li class="4bags" data-value="4">
    <h3>4 BAGS, $55</h3>
    <img src="img/4bags.png">
  </li>
</ul>

What am I doing wrong?

Calvin Nunes
  • 6,162
  • 3
  • 18
  • 41
  • Where is that script in relation to the html on the page? Is it in the head? – Taplar May 08 '18 at 17:10
  • Yes it's in the head – Kylie Ritchie May 08 '18 at 17:14
  • 1
    Then put your script in a document ready or move it to the bottom of the body. Your elements do not exist at the point that the head is being parsed into the dom for it to find them and bind on – Taplar May 08 '18 at 17:14
  • https://jsfiddle.net/reyffexs/ your code works fine, provided you bind after the elements exist on the page – Taplar May 08 '18 at 17:20

1 Answers1

2

change your code to like this

    $("ul.quantity-grid li").click(function(){
       
        $('ul.quantity-grid li').removeClass("active");
        $(this).addClass("active");
    });
.quantity-grid {
 background: red;
}
 .quantity-grid li.active{
            border:4px solid #fff;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="quantity-grid">
            <li class="1bag" data-value="1">
                <h3>1 BAG, $35</h3>
                <img src="img/1bag.png">
            </li>

            <li class="2bags" data-value="2">
                <h3>2 BAGS, $45</h3>
                <img src="img/2bags.png">
            </li>

            <li class="3bags" data-value="3">
                <h3>3 BAGS, $65</h3>
                <img src="img/3bags.png">
            </li>

            <li class="4bags" data-value="4">
                <h3>4 BAGS, $55</h3>
                <img src="img/4bags.png">
            </li>
        </ul>
patelarpan
  • 4,756
  • 15
  • 21