Help, with a script that would change the contents of the main div every n seconds.

Suppose there is a <div class="a"> <img src="href"> <p>text</p> <div>

and I have several such blocks, all with class a, too, but they have different values ​​for href and text. Tried with innerHtml, did not work

Closed due to the fact that the essence of the issue is incomprehensible to the participants by Grundy , dirkgntly , Denis , sercxjo , Ivan Pshenitsyn 23 Aug '16 at 14:11 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • 2
    What exactly did not work out? Show the code of your attempts. - Sergey Gornostaev
  • one
    Every n seconds changed to what, do not you understand? - Ivan Pshenitsyn

2 answers 2

I can offer this solution to your problem.

HTML

 <div class="text"> <div class="a"><img src="href"> <p>text</p> </div> <div class="a"><img src="href"> <p>text</p> </div> <div class="a"><img src="href"> <p>text</p> </div> </div> 

Js

  $(document).ready(function() { $('.text .a').eq(0).addClass('active').fadeIn(1000);// Показываем первый блок, можно и не первый, если прописать нужную цифру в eq() setInterval('blockAnimate();', 5000);// Вызываем функцию для смены блока каждые 5 секунд }); // Функция для смены блоков, показывает блоки по очереди, начальный блок задаётся выше function blockAnimate() { var length = $('.text .a').length - 1; $('.text .a').each(function(index) { if($(this).hasClass('active') && index != length) { $(this).removeClass('active').fadeOut(1000).next('.a').addClass('active').fadeIn(1000); return false; } else if (index == length) { $(this).removeClass('active').fadeOut(1000); $('.text .a').eq(0).addClass('active').fadeIn(1000); return false; } }); }; 

CSS

 .a { position: absolute; display: none; } 
  • Thanks, it turned out! - Apemother
  • I only for some reason show all the blocks at once, and then they appear in turns - Apemother
  • and when a new element is added later, it gets to the end of the document, then the first one is deleted and then only the first place is inserted - Apemother
  • @Apemother Indeed, I forgot to specify that in CSS you need to add another description, then everything should work correctly. Added the necessary code in the answer. - Legionary
  1. I would assign an id attribute to this element so that you can quickly get to it.
  2. If you need to do something every few seconds, you need to use timers, for example, a set interval.
  3. You must write innerHTML, not innerHtml.

I do it with innerHTML.