I am working with an html component that appears twice on a page.
The issue I am having is that when I click one component to toggle it's content (like an accordion) both components toggle simultaneously.
How can I rewrite the JS to toggle each component when I click them separately, without giving the components different classes and rewriting the js twice?
This is what I have so far;
var bindEventsToUI = function () {
$(".details").click(function(e){
$(".content").slideToggle("slow", function() {
$(e.target).hide().siblings().show();
});
});
};
Try this:
$(".details").click(function(e) { $(this).children(".content").slideToggle("slow"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='details'>Testing 123 <div class='content'>> Content 123</div> </div> <div class='details'>Testing 456 <div class='content'>> Content 456</div> </div>
You will need to have a different identifier for each element. I would recommend an id
:
var bindEventsToUI = function () {//element) {
$("#id1 .details").click(function(e){
$("#id1 .content").slideToggle("slow", function() {
$(e.target).hide().siblings().show();
});
});
$("#id2 .details").click(function(e){
$("#id2 .content").slideToggle("slow", function() {
$(e.target).hide().siblings().show();
});
});
//..and so on
};
Or, you could use the closest
function:
var bindEventsToUI = function () {//element) {
$(".details").click(function(e){
$(this).closest(".content").slideToggle("slow", function() {
$(e.target).hide().siblings().show();
});
});
};
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.