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)
$("#navBarBehandeling").on('click',CheckDropDown);
function CheckDropDown(){
var t = $(this);
if(t.attr('aria-expanded')=='false'){
$('main').addClass("mt-9");
}
else{
$('main').removeClass("mt-9");
}
}
CodePudding user response:
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')){
$('main').addClass("mt-9").text('addClass');
} else{
$('main').removeClass("mt-9").text('removeClass');
}
}
// your code
$("#navBarBehandeling2").on('click',CheckDropDown2);
function CheckDropDown2(){
var t = $(this);
if(t.attr('aria-expanded')=='false'){
$('main2').addClass("mt-9").text('addClass');
}
else{
$('main2').removeClass("mt-9").text('removeClass');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="javascript:undefined" id="navBarBehandeling">test</a>
<main></main>
<br><br>
<a href="javascript:undefined" id="navBarBehandeling2">Your code</a>
<main2></main2>
CodePudding user response:
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");
}
}
});