• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

29
Views
I want to create a jQuery loop out of this function instead of copying this function over and over for 12 times

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!

about 2 months ago ·

Juan Pablo Isaza

1 answers
Answer question

0

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.

about 2 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.