V
V
Valery2015-10-06 13:02:00
JavaScript
Valery, 2015-10-06 13:02:00

How to shorten the code into one function?

$(document).ready(function () {	
  $('.txt-1').click(function() { 
    $('.txt').removeClass('txt-active'); 
    $('.txt-1').addClass('txt-active'); 
    $('.pull-right .img').hide(); 
    $('.pull-right .img-1').fadeIn(); 
    return false; 
  });
  $('.txt-2').click(function() { 
    $('.txt').removeClass('txt-active'); 
    $('.txt-2').addClass('txt-active'); 
    $('.pull-right .img').hide(); 
    $('.pull-right .img-2').fadeIn(); 
    return false; 
  });
  $('.txt-3').click(function() { 
    $('.txt').removeClass('txt-active'); 
    $('.txt-3').addClass('txt-active'); 
    $('.pull-right .img').hide(); 
    $('.pull-right .img-3').fadeIn(); 
    return false; 
  });
});


Can somehow correctly implement through
var count = 0;
count++;

But how exactly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolay Talanov, 2015-10-06
@Lacett1

You remove nafig txt-1/txt-2/txt-n classes from elements, instead you add data attributes to them with IDs. Alya data-id="2". Through delegation, you hang one handler on all .txt elements. Inside, you get their id from the attribute, then you remove the active class from the active element, add it to the current (clicked) one, then hide all .img (here, in fact, it’s also better to change from hide / fadein to classes, but this is not my problem anymore) and show the one you need using the id you got earlier.

$(document).on("click", ".txt", function(e) {
  e.preventDefault();

  var id = $(this).data("id");

  $(".txt.txt-active").removeClass("txt-active");
  $(this).addClass("txt-active");
  $(".pull-right .img").hide();
  $(".pull-right .img-"+id).fadeIn();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question