If the section has an active class, then add its id to the body as a class?
I would be grateful if you can help with this, I cannot decide. I'm trying to create a function: "if any section has class" active "=> take this section id then add it to the body as a class element, otherwise remove it"
This code is below, but it doesn't work as expected or when I go to the next section, the new class is not added and the previous one is removed.
<body class="">
<section id="home" class="active">
</section>
<section id="about" class="">
</section>
</body>
if ($('section').hasClass('active')) {
var dataSection = $('section').attr('id');
$body.addClass(dataSection.replace('#', '') + '-active');
} else {
$body.removeClass('home-active');
}
source to share
When you use $('section').attr('id')
that will always return the id
first section, you need to use this
internally section
in:
$('section').attr('id');
Should be:
$(this).attr('id');
This way it will get the ID of the current section. There is also no need to replace both lines, which can be concatenated into:
$body.addClass($(this).attr('id') + '-active');
NOTE. You can always get the active section using only the selector, for example:
$('section.active')
Hope it helps.
source to share
Will actually $('section').attr('id')
give you the id attribute without #
, you can use it directly, you can see the body class
changed accordingly in the following demo:
if ($('section').hasClass('active')) {
$("body").addClass($('section').attr('id') + '-active');
} else {
$("body").removeClass('home-active');
}
console.log($("body").attr('class'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="">
<section id="home" class="active">
</section>
<section id="about" class="">
</section>
</body>
Note:
Note that you are using $body
which you have not yet declared, use $("body")
instead to reference the body of the document.
source to share