T
T
Timur2019-05-22 03:07:00
JavaScript
Timur, 2019-05-22 03:07:00

How to write such code in a compact way?

Guys, js is very bad. There is this script:

$('#cont-one').on('click', function(event) {
         $("#one-cont").addClass("activecont")
         $("#two-cont").removeClass("activecont")
         $("#three-cont").removeClass("activecont")
         $("#four-cont").removeClass("activecont")
         
         event.preventDefault();
    });
    $('#cont-two').on('click', function(event) {
         $("#one-cont").removeClass("activecont")
         $("#two-cont").addClass("activecont")
         $("#three-cont").removeClass("activecont")
         $("#four-cont").removeClass("activecont")
         
         event.preventDefault();
    });
    
    $('#cont-three').on('click', function(event) {
         $("#one-cont").removeClass("activecont")
         $("#two-cont").removeClass("activecont")
         $("#three-cont").addClass("activecont")
         $("#four-cont").removeClass("activecont")
         
         event.preventDefault();
    });
    
    $('#cont-four').on('click', function(event) {
         $("#one-cont").removeClass("activecont")
         $("#two-cont").removeClass("activecont")
         $("#three-cont").removeClass("activecont")
         $("#four-cont").addClass("activecont")
         
         event.preventDefault();
    });
});

Help make it normal, please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex-1917, 2019-05-22
@alex-1917

Another question about tabs... well... already the seventh one in a week.
When the graduates already stand behind the machine, they ate all the baldness)))
here www.jooom.ru/toster/toster_10.html
or here www.jooom.ru/toster/toster_6.html

A
Anton Shvets, 2019-05-22
@Xuxicheta

[
  $("#one-cont"),
  $("#two-cont"),
  $("#three-cont"),
  $("#four-cont"),
 ]
  .forEach((target, i, tabs) => target.on(
    'click',
    (event) => {
      tabs.forEach(tab => tab.removeClass("activecont"));
      target.addClass("activecont");
      event.preventDefault();
    },
  ));

like this
Creates 4 functions with closures, if desired, can be optimized into one function if there is such a need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question