javascriptphpjqueryswiper.js

swiper-bundle.min slider menu - save active class on item after click on it


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>


Solution

  • When you are setting the localStorage.setItem('toggleState') the value inserted is a boolean, it has the class active or it not has the class active.

    You need to save the id of the element to make it active again when consulting the localStorage.getItem, otherwise you get the boolean 0/1.

    You can do it with: localStorage.setItem('toggleState', $(this).attr("id"));

    It saves the id attribute of the element in the toggleState.