Unfortunately, this is a remarkable stupid question. However, I could not figure out how to make a working click counter für the Bootstrap carousel button. The problem is the span element for the previous and next icons.
The button counter does not count clicks on the repective span element.
$('button').click(function(btn) { btn.target.dataset.click_counter_hidden = (+btn.target.dataset.click_counter_hidden || 0) + 1; $('#click_search_left').val($('button[data-id="slider_left"]').attr("data-click_counter_hidden") || 0); $('#click_search_right').val($('button[data-id="slider_right"]').attr("data-click_counter_hidden") || 0);
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel" data-bs-interval="false"> <div class=class="carousel-item active"> <div class="carousel-item" id="example1"> <img id="example_1" src="https://picsum.photos/200/300" class="d-block w-100" alt="example_1"> </div> <div class="carousel-item" id="example2"> <img id="example_2" src="https://picsum.photos/200/300" class="d-block w-100" alt="example_2"> </div> <div class="carousel-item" id="example3"> <img id="example_3" src="https://picsum.photos/200/300" class="d-block w-100" alt="example_1"> </div> </div> <button type="button" id='slider_left' data-id="slider_left" class="carousel-control-prev tracked_element" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" id="prev_icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button type="button" id='slider_right' data-id="slider_right" class="carousel-control-next tracked_element" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" id="next_icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <input type="hidden" name="click_search_left" id="click_search_left" value="0" /> <input type="hidden" name="click_search_right" id="click_search_right" value="0" />
Advertisement
Answer
Add your counter data attribute to the two buttons (this is just to help initialize).
<button data-click_counter_hidden="0">
Check to see if click event was on button. If not it must’ve been the child span element so get the parent (the button).
$('button').on('click', function(e){ $t = $(e.target); if (!$t.is('button')){ $t = $t.parent(); } clicks = parseInt($t.data('click_counter_hidden')) + 1; $t.data('click_counter_hidden', clicks); // display counter value elsewhere if needed });