I need some help with creating a loop in this jQuery function. I have some elements on my HTML page with the attribute [level-data="l1"]
, and I use them in my function to make some changes on the page. I have 12 different attributes starting with the [level-data="l1"]
and finishing with the [level-data="l12"]
. What I want is to create a jQuery loop instead of copying this function over and over for 12 times, each element will have a different [level-data='ln']
attribute, where n is a number from 1 to 12.
Here is my code:
$('.chart-level[level-data="l1"]').on("click", function () {
$('.chart-level').removeClass('active');
$('.chart-levels-items .level-info').removeClass('active');
$(this).addClass('active');
$('.chart-levels-items .level-info[level-data="l1"]').addClass('active');
$('.chart-slider-item.page_slider').removeClass('shown');
$('.chart-slider-item.page_slider[level-data="l1"]').addClass('shown');
$('.chart-slider-item.popup_slider').removeClass('shown');
$('.chart-slider-item.popup_slider[level-data="l1"]').addClass('shown');
if(window.matchMedia('(max-width: 768px)').matches){
$([document.documentElement, document.body]).animate({
scrollTop: $(".chart-levels-items .level-info[level-data='l1']").offset().top
}, 2000);
}
});
Thank you in advance!
Juan Pablo Isaza
You don't need a loop. Use .chart-level[level-data]
as the selector and read the level-data
attribute of the clicked element. [...]
is an attribute selector which selects elements that have a certain attribute.
Note that level-data
is an invalid attribute. You can use data-*
attributes instead. i.e. change it to data-level
. Then you can use $(this).data('level')
for reading the value of the data-level
attribute.
$('.chart-level[data-level]').on("click", function () {
var level = $(this).data('level')
$('.chart-levels-items .level-info[data-level="' + level + '"]').addClass('active');
// ...
});
In case that you are using the attribute just for selecting related elements to the clicked element, then you should consider using jQuery traversal methods (like parent
, siblings
, ...) for selecting the target elements instead.