i am using swiper-bundle to create a slider horizontal menu .
swiper-bundle.min.css and swiper-bundle.min.js .
i added an active class to the first item and trying to give each item the active class
after click on it and remove active from the siblings .
it works to give active class to items but not save the active on the clicked item .
how to save active on item after click on it ?
<div class="pt_sec_nav_cats">
<div class="container-fluid">
<div class="swiper pt_sec_nav_slide_prnt">
<div class="swiper-wrapper pt_sec_nav_slide">
<div class="swiper-slide active">
<a class="sof-swiper-link" href="index.php">home</a>
</div>
<?php foreach ( $items as $i => $item ) :
$route = YendifVideoShareRoute::getCategoryRoute( $item, (int) $params->get( 'itemid', 0 ) );
$item_link = Route::_( $route );
?>
<div class="swiper-slide " >
<a href="<?php echo $item_link; ?>" class="sof-swiper-link">
<?php echo YendifVideoShareHelper::Truncate( $item->title, $params->get( 'title_length', 0 ) );?>
</a>
</div>
<?php endforeach; ?>
</div>
<button class="swiper-button-next sof-swiper-button"></button>
<button class="swiper-button-prev sof-swiper-button"></button>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$(".swiper-slide").click(function() {
$(this).addClass("active").siblings().removeClass("active");
localStorage.setItem('toggleState', $(this).hasClass('active'));
});
const toggleState = localStorage.getItem('toggleState');
if (toggleState === 'true') {
const activeLi = $("#" + toggleState);
activeLi.addClass("active");
}
});
</script>
2
Answers
localStorage.setItem('toggleState', $(this).attr("id"));
by @Roy Bogado
When you are setting the
localStorage.setItem('toggleState')
the value inserted is a boolean, it has the classactive
or it not has the classactive
.You need to save the
id
of the element to make it active again when consulting thelocalStorage.getItem
, otherwise you get the boolean 0/1.Yo can do it with:
localStorage.setItem('toggleState', $(this).attr("id"));
It saves the id attribute of the element in the
toggleState
.