So, on my website's home page I have a list of services. The idea is that when you click on one of them, a description appears alongside it relating to that service. However, clicking on said buttons doesn't do anything and I'm not entirely sure why. This JS function is the same as what I'm using for my menu button, which performs perfectly.
I'm no professional with code and would still describe myself as a beginner so any help on the matter is very much appreciated!
$(document).ready(function() { $('.video-btn').click(function() { $('description-video').toggleClass('active'); }) $('.animation-btn').click(function() { $('description-animation').toggleClass('active'); }) })
.description { width: 600px; font-size: 1.4em; line-height: 1.2em; font-weight: 400; color: #f4f4f4; padding-left: 1em; border-left: 4px solid #e0bd8c; } #description-video, #description-animation { display: none; } #description-video.active, #description-animation.active { display: inherit; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="service-list"> <li id="video-btn"><a href="#">Video</a></li> <li id="animation-btn"><a href="#">Animation</a></li> </ul> <p class="description" id="description-video"> Text goes here... </p> <p class="description" id="description-animation"> Text goes here... </p>
2 things :
In clicks identifiers they are classes, but you defined it as ids in your html
$('#video-btn').click(function() {
$('#animation-btn').click(function() {
Your forgot the prefix on toggleClass identifiers
$('#description-video').toggleClass('active');
$('#description-animation').toggleClass('active');
You need to delegate and use data-attributes
$(function() { $('.service-list').on("click",'.btn a', function() { $("#"+this.dataset.desc).toggleClass('active'); }); });
.description { width: 600px; font-size: 1.4em; line-height: 1.2em; font-weight: 400; color: #f4f4f4; padding-left: 1em; border-left: 4px solid #e0bd8c; } #description-video, #description-animation { display: none; } #description-video.active, #description-animation.active { display: inherit; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="service-list"> <li class="btn"><a href="#" data-desc="description-video">Video</a></li> <li class="btn"><a href="#" data-desc="description-animation">Animation</a></li> </ul> <p class="description" id="description-video"> Text goes here... </p> <p class="description" id="description-animation"> Text goes here... </p>
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.