I'm trying to add the class "open-height" to a div and keep the class when I click in between the list items. Then remove the class when you click the same list item.
$('#navlist a').click(function(e) {
e.preventDefault(); //prevent the link from being followed
$('#navlist a').removeClass('selected');
$(this).addClass('selected');
if($(this).hasClass('selected')) {
$('.single-course-wrapp').toggleClass('open-height');
} else {
$('.single-course-wrapp').addClass('open-height');
}
});
You could achieve that using data-*
attributes, by storing the id of li on data-opened-by
attribute in the div then make condition to remove the class from it just when the clicked item has the same id stored on data attribute :
$('#navlist a').click(function(e) { e.preventDefault(); //prevent the link from being followed $('#navlist a').removeClass('selected'); $(this).addClass('selected'); if($('.single-course-wrapp').hasClass('open-height')){ var opener_id = $('.single-course-wrapp').data('opened-by'); if($(this).parent().attr('id')==opener_id){ $('.single-course-wrapp').removeClass('open-height'); } }else{ $('.single-course-wrapp').addClass('open-height'); $('.single-course-wrapp').data('opened-by', $(this).parent().attr('id')); } });
.nav { color: green; } .selected { color: red; } .open-height{ height:200px; width:200px; background:#000; transition: all 0.6s ease 0.3s; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="navlist"> <li id="home"><a class="nav" href="home">Home</a></li> <li id="about"><a class="nav" href="about-us">About Us</a></li> <li id="service"><a class="nav" href="about-us">Service</a></li> <li id="contact"><a class="nav" href="about-us">Contact</a></li> </ul> <div class="single-course-wrapp"> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.