Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Class doesn't get added on first click

I add a classname with Jquery, and it works, but only starts working AFTER my first click. The code only addes the 'class' attribute the first time, but without the value. Can anyone see what I do wrong? (the class just add's a top margin in CSS)

(function(){
    $(document).ready(Setup)

    function Setup(){
        $("#navBarBehandeling").on('click',CheckDropDown);
    }
    $("#navBarBehandeling").on('click',CheckDropDown);
    function CheckDropDown(){
        var t = $(this);
        if(t.attr('aria-expanded')=='false'){
           $('main').addClass("mt-9");

        }
        else{
            $('main').removeClass("mt-9");
        }

    }
}()

And here's my css:

.mt-9{
    margin-top: 9rem;
}

and here's my html:

<head>
   CDN's for Jquery and bootstrap
</head>
<body>
    <header>
        <div id="navBarBehandeling"> navbar with dropdown here></div>
    </header>
    <main>
        <p> blablabla </p>
    </main>
</body>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can just do !t.attr('aria-expanded') to make it work

$("#navBarBehandeling").on('click',CheckDropDown);
function CheckDropDown() {
    var t = $(this);

    if (!t.attr('aria-expanded')) {
       console.log('addClass');
       $('main').addClass("mt-9");
    } else{
      console.log('removeClass');
      $('main').removeClass("mt-9");
    }
}
.mt-9{
    margin-top: 9rem;
}
<!DOCTYPE html>
<html>
  <head>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
      <header>
          <div id="navBarBehandeling"> navbar with dropdown here></div>
      </header>
      <main>
          <p> blablabla </p>
      </main>
  </body>
</html>

about 4 years ago · Juan Pablo Isaza Report

0

Use document ready like this:

$(document).ready(function () {
      $("#navBarBehandeling").on("click", CheckDropDown);
      function CheckDropDown() {
        var t = $(this);
        if (t.attr("aria-expanded") == "false") {
          $("main").addClass("mt-9");
        } else {
          $("main").removeClass("mt-9");
        }
      }
    });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!