I would be grateful if you help with this thing, I can't resolve. I am trying to create a function: "if any section has class "active" => take this section's id then add it to body as a class element otherwise remove"
This the code below, but it's not working properly or when I scroll to next section new class is not being added and previous one 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');
}
Try using this here.
if( $(something).hasClass("active") ){
var grabId = $(this).attr("id");
$("body").attr("id", grabId);
}
When you use $('section').attr('id') that will always return the id of the first section, You need to use this inside of section in :
$('section').attr('id');
Should be :
$(this).attr('id');
So it will get the id of the current section, Also no need for the replace the both lines could be combined to :
$body.addClass($(this).attr('id') + '-active');
NOTE : You could always get the active section using just selector like :
$('section.active')
Hope this helps.
Actually $('section').attr('id') will give you the id attribute without # you can use it directly, you can see body class changed accordingly in the folowing 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 haven't declared, use $("body") instead to refer document body.