I have a slide navigation script that allows me to navigate to a particular slide using an "nth-child(#) that triggers a click event.
Each button currently has its own slide reference, i.e Slide-1 button will link to nth-child(1) and so forth through to slide/button 8
I am looking for ways to optimise the below script using a loop or something similar so that it is more manageable and still keeps the same functionality.
<script>
jQuery(document).ready(function( $ ) {
var selector = '.activelinks a';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
});
$("#Slide-1").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(1)").trigger("click");
});
$("#Slide-2").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(2)").trigger("click");
});
$("#Slide-3").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(3)").trigger("click");
});
$("#Slide-4").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(4)").trigger("click");
});
$("#Slide-5").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(5)").trigger("click");
});
$("#Slide-6").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(6)").trigger("click");
});
$("#Slide-7").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(7)").trigger("click");
});
$("#Slide-8").on("click", function(e) {
e.preventDefault();
$(".et-pb-controllers a:nth-child(8)").trigger("click");
});
});
</script>
CodePudding user response:
you can give a class to all slide buttons like : slideBtn
then :
jQuery(document).ready(function ($) {
var selector = ".activelinks a";
$(selector).on("click", function () {
$(selector).removeClass("active");
$(this).addClass("active");
});
$(".slideBtn").on("click", function (e) {
e.preventDefault();
var slideNumber = e.target.id.replace( /^\D /g, '');
$(".et-pb-controllers a:nth-child(" slideNumber ")").trigger("click");
});
});