Marco Koivisto
Marco Koivisto

Reputation: 52

Using same click function for multiple elements (Jquery)

Hi Im having troubles with getting the following to work. Only the first element works, how should I think?

<div class="hi">
    <a id="tabBtn" href="javascript:void(0)"></a>
</div>
<div class="hi">
    <a id="tabBtn" href="javascript:void(0)"></a>
</div>
<div class="hi">
    <a id="tabBtn" href="javascript:void(0)"></a>
</div>

<script>
    $('#tabBtn').on("click",function(){
        if ($(this).parent('.hi').css('max-height') == '65px'){
            $(this).parent(".hi").addClass('open');
        }
        else{
            $(this).parent(".hi").removeClass('open');
        }
    })
</script>

Upvotes: 0

Views: 257

Answers (2)

Jacob G
Jacob G

Reputation: 14152

Using the same id on multiple elements is invalid, use a class instead:

    $('.tabBtn').on("click", function() {
      if ($(this).parent('.job').css('max-height') == '65px') {
        $(this).parent(".job").addClass('open');
      } else {
        $(this).parent(".job").removeClass('open');
      }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="hi">
  <a class="tabBtn" href="javascript:void(0)">Hello</a>
</div>
<div class="hi">
  <a class="tabBtn" href="javascript:void(0)">Hello2</a>
</div>
<div class="hi">
  <a class="tabBtn" href="javascript:void(0)">Hello3</a>
</div>

Upvotes: 3

Zamboney
Zamboney

Reputation: 2010

first thing first id attribute should be ONCE per page

having say that all you need to do is work on the on function from the document and in a selecter way like so

$(document).on("click",".tabBtn",function(){
  //do work
})

Upvotes: 1

Related Questions