Switch content of DIV with another set DIVs with a timer - javascript

I have 3 divs in a html page, 2 divs should be hiddent always but theire content should be displayed in another div and this content should be changed every x seconds. Hows that possible using jquery/javascript?
<div id="contentA">
<!-- Some contents goes here, and it should be hidden -->
</div>
<div id="contentB">
<!-- Some contents goes here, and it should be hidden -->
</div>
<div id="displayArea">
<!-- switch between contentA and contentB on a timer say every 5 seconds -->
</div>

Do not use the .html() function to copy content from one place to another. HTML is a serialisation format designed to carry DOM structures from a server to a client. Once the page is in a DOM structure you should manipulate that DOM structure directly using DOM methods. Using .html() to serialise a DOM node and then recreate it somewhere else risks losing things like event handlers, other hidden data, etc.
On that basis, to copy the current contents of a div into another:
var $contents = $('#contentA').contents().clone(); // copy the source element's contents
$('#displayArea').empty().append($contents); // drop them into the destination
In full:
(function() {
var delay = 3000;
var state = 0;
(function next() {
state = 1 - state;
var src = state ? '#contentA' : '#contentB';
var $contents = $(src).contents().clone();
$('#displayArea').empty().append($contents);
setTimeout(next, delay);
})();
})();

Try this :)
<div id='a' style='display: none;'>this is a</div>
<div id='b' style='display: none;'>this is b</div>
<div id='show'></div>
<script>
$(document).ready(function(){
var count = 0;
var content = '';
var j = setInterval(function () {
count++;
if(count%2===0){
content = $('#a').html();
}else{
content = $('#b').html();
}
$('#show').html(content);
}, 5000);
});
</script>

Try this:
var toggle = false;
$("#displayArea").html($("#contentA").html());
setInterval(function() {
$("#displayArea").html(toggle ? $("#contentA").html() : $("#contentB").html());
toggle = !toggle;
}, 5000);
Working DEMO

I don't know if this is what you need but this script should work:
check = true;
$(document).ready(function(){
setInterval(function(){
if(check) {
check = false;
$('#displayArea').html("a");
}
else {
check = true
$('#displayArea').html("b");
}
}, 5000);
});

function doSlides() {
var msg = messages.shift();
messages.push(msg);
$('#displayArea').html(msg);
};
var messages = [
$('#contentA').find('p').html(),
$('#contentB').find('p').html()
];
Demo:
http://jsfiddle.net/8Ux3L/

Here's one way to do it using setInterval():
var divs = $('div[id^="content"]').hide(),
i = 0;
function cycle() {
$("#displayArea").html(divs.eq(i).html());
i = ++i % divs.length; // increment i, and reset to 0 when it equals divs.length
}
setInterval(cycle, 2000); //Cycle every 2 seconds
Wrapping in a self executing function:
(function cycle() {
$("#displayArea").html(divs.eq(i).html());
i = ++i % divs.length; // increment i, and reset to 0 when it equals divs.length
setTimeout(cycle, 2000);
})();
DEMO

Try following code
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script>
var divSelected = "A";
function switch1()
{
if (divSelected == "A")
{
$("#displayArea").text($("#contentA").text());
divSelected = "B";
}
else
{
$("#displayArea").text($("#contentB").text());
divSelected = "A";
}
}
$(document).ready(function()
{
var test = setInterval( "switch1()" , 5000);
});
</script>
</head>
<body>
<div id="contentA" style = "display:none;">
Contect A
</div>
<div id="contentB" style = "display:none;">
Content B
</div>
<div id="displayArea">
</div>
</body>
</html>

Use an interval to trigger a function every x seconds, then jQuery replaceWith to swap the divs. If you don't want to replace the actual node but just the contents, then .html() is probably the way to go.

Related

How to call a function in external script file from HTML

I'm trying to call a javascript function in my HTML index file and I can't get it to work.
This is my html file that I'm trying to call a function from.
<div class="main">
<h1 class="header-main" onload="HeaderTyper('Welcome', this)">
<noscript>no javascript</noscript>
</h1>
</div>
<script type="text/javascript" src="script.js"></script>
And this is the script.
function HeaderTyper(message, element){
var i = 0;
var speed = 50;
if (i < message.length) {
element.innerHTML += message.charAt(i);
//play keystroke sound
i++;
setTimeout(HeaderTyper, speed);
}
}
I'm trying to get a typewriter effect style header. I'm planning to add some keystroke sounds, but first I need to figure out how to actually type it out in the header tag. The code won't type out the message I'm passing in argument. What did I do wrong ? Thank you for any help.
After the HTML page ends (As #johannchopin explained), import the file and then add an event listener (as #aaronburrows explained).
<body>
<div class="main">
<h1 class="header-main">
<noscript>no javascript</noscript>
</h1>
</div>
</body>
</html>
<script type="text/javascript" src="script.js"></script>
<script>
let h1 = document.querySelector('.header-main');
h1.addEventListener('load', HeaderTyper("Welcome", h1, false));
</script>
Also, I fixed the function, it was missing the parameters.
function HeaderTyper(message, element, i) {
var speed = 50;
if (i < message.length) {
console.log(message.charAt(i))
element.innerHTML += message.charAt(i);
//play keystroke sound
setTimeout(function(){ HeaderTyper(message,element,++i)}, speed);
}
}
You're attempting to bind a function call before it is loaded into the browser. Remove the onload from the HTML and add an event listener to the script.
According to this solution, The onload event can only be used on the document(body) itself. Best way to achieve this is to call the function in a <script> tag just before the </body> closing tag:
<div class="main">
<h1 class="header-main">
<noscript>no javascript</noscript>
</h1>
</div>
<script>
function HeaderTyper(message) {
var i = 0;
var speed = 50;
var element = document.querySelector('.header-main');
if (i < message.length) {
element.innerHTML += message.charAt(i);
//play keystroke sound
i++;
setTimeout(HeaderTyper, speed);
}
}
HeaderTyper('Welcome');
</script>
Ok, hi there.
function HeaderTyper(message, element){
alert('script loaded') //<---
var i = 0;
I put this line at the beginning of the script to make sure it works. And it's not.
Why?
Because you just made your function but doesn't call it.
First way to solve this - put ur function in the "script" of HTML doc. And call it after, like
<script>
function HeaderTyper(message) {
let i = 0
let speed = 50
let element = document.querySelector('.header-main')
if (i < message.length) {
element.innerHTML += message.charAt(i)
i += 1
setTimeout(HeaderTyper, speed)
}
}
HeaderTyper('Welcome') //<---
</script>
Second way - put HeaderTyper() at the end of script.js file, so the function start, but you need to make a link for "message" and "element".
setTimeout(HeaderTyper, speed);
}
}
HeaderTyper(someMessage, someElement) //<---

Trying to get the total number of divs in the html document jquery

I am printing several div with php. Then I check how many divs there are with jquery. When the time code runs, I remove box_num_3 from the DOM. But the total div number still 5. I think it was because the DOM in the background was not renewed. How do i solve this problem?
<?php
for($i=0; $i<5; $i++){
echo '<div class="box box_num_'.$i.'">Div</div>';
}
?>
<script>
var interval = setInterval(function(){
var box_nums = $(".box").length;
console.log("total box->"+box_nums);
}, 1000);
</script>
<script>
//TIME CODE
var timer = 5;
var cd_timer = setInterval(function(){
timer-=1;
console.log(timer);
if(timer==0){
clearInterval(cd_timer);
$(".box_num_3").fadeOut(1000);
}
},1000);
</script>
Edit: Solved problem, thanks to everyone who answered.
$(".box").fadeOut();
//instead
$(".box_num_3").remove();
Simply use length using the selector with visibility, after wait for the elements to hide.
// A $( document ).ready() block.
$( document ).ready(function() {
var total_div_after = 0;
$('div.fade').fadeOut(1000, function() {
total_div_after = $('div').not(":hidden").length;
console.log('After fade:', total_div_after);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">Visible</div>
<div class="box">Visible</div>
<div class="box">Visible</div>
<div class="box fade">(fade)</div>
var container_div = document.getElementById('id_of_container_div');
var count = top_level_div.getElementsByTagName('div').length;
To count all divs of a specified class do:
var numItems = $('.item').length;

Set jquery delay from html data

I'm trying to set individual duration times from a value in the html that the text is displayed before displaying the next. I thought maybe I could do something with setting a variable (howlong) for the jquery .delay, but it's only getting the value by the first "data-howlongtime" for the rest of them. JSFiddle. What am I doing wrong besides everything?
<div id="aboutid" data-howlongtime="10000">
<p class="abouts">Less delay</p>
</div>
<div id="aboutid" data-howlongtime="20000">
<p class="abouts">Long delay</p>
</div>
<style>.abouts {display: none;}</style>
<script>
var delayabout=1700;
var howlong = $('#aboutid').data('data-howlongtime');
(function() {
var abouts = $(".abouts");
var aboutIndex = -1;
function showNextabout() {
++aboutIndex;
abouts.eq(aboutIndex % abouts.length)
.fadeIn(2000)
.delay(howlong)
.fadeOut(2000, showNextabout);
}
setTimeout(function(){
showNextabout();
}, delayabout);
})();
</script>
Try this, you are actually taking the howlongtime at the top, one time only, you need to check it for every iteration.
var delayabout = 1000;
(function() {
var abouts = $(".abouts");
var aboutIndex = -1;
function showNextabout() {
++aboutIndex;
var $about = abouts.eq(aboutIndex % abouts.length),
howLong = $about.parents('div#aboutid').data('howlongtime');
$about.fadeIn(2000)
.delay(howLong)
.fadeOut(2000, showNextabout);
}
setTimeout(function() {
showNextabout();
}, delayabout);
})();

create simple rotation with pause

How can I cycle through a series of elements, adding a class, pausing then removing the class and moving on to the next element. I have tried setInterval and I have tried setTimeout, but cannot seem to get it to work.
My Javascript
var numpromos = $('.promoteBlock').length;
var promonum = 1;
while (numpromos > promonum){
setInterval(function() {
$('#promoteCont .promoteBlock').fadeOut().removeClass('active');
$('#promoteCont #promo'+promonum).addClass('active');
}
}, 3000);
promonum++;
}
My HTML
<div id="promoteCont">
<div id="promo1" class="promoteBlock">Promotion No.1</div>
<div id="promo2" class="promoteBlock">Second Promo</div>
<div id="promo3" class="promoteBlock">Another one</div>
</div>
function playNext(){
console.log("playNext");
var active = $('#promoteCont').find(".promoteBlock.active");
if( active.length == 0 )
active = $(".promoteBlock:eq(0)");
var fout = active.next();
if( fout.length == 0 )
fout = $(".promoteBlock:eq(0)");
active.fadeOut().removeClass('active');
fout.fadeIn().addClass('active');
setTimeout(function(){
playNext();
},3000);
}
setTimeout(function(){
playNext();
},3000);
http://jsfiddle.net/p1c3kzj7/
Take things out of the while loop. You only need to set the interval once. Perform your state calculation (which item is selected) within the callback method itself. See below, which I believe is what your looking for.
// Global variables to maintain state... I'm sure I'll get some comments about these :p
var numpromos = $('.promoteBlock').length;
var promonum = 1;
$document.ready(function()
{
setInterval(function() {
$('#promoteCont .promoteBlock').fadeOut().removeClass('active');
$('#promoteCont #promo'+promonum).addClass('active');
promonum++;
if(promonums > numpromos)
promonum = 1;
}, 3000);
});

javascript image change after 'x' amount of time

How would I go about adding a timer to this js so images would change automatically after 'x' amount of time. As it stands the change is made via 'a href' with the 'rel' attribute, but that function with the 'rel' is still required.
js:
$(document).ready(function (){
$('#button a').click(function(){
var integer = $(this).attr('rel');
$('#myslide .cover').css({left:-1476*(parseInt(integer)-1)}).hide().fadeIn(); /*----- Width of div mystuff (here 160) ------ */
$('#button a').each(function(){
$(this).removeClass('active');
if($(this).hasClass('button'+integer)){
$(this).addClass('active')}
});
});
});
html:
<div id="myslide">
<div class="cover">
<div class="mystuff">
<img src="images/header_01.jpg" rel="1"></img>
<img src="images/header_02.jpg" rel="1"></img>
<img src="images/header_03.jpg" rel="1"></img>
</div>
</div>
You should consider using setInterval and and an array of images to change the source. This will force the image to loop continuously
var images = ['header_01.jpg','header_02.jpg','header_03.jpg'],
index = 0, // starting index
maxImages = images.length - 1;
var timer = setInterval(function() {
var curImage = images[index];
index = (index == maxImages) ? 0 : ++index;
// set your image using the curImageVar
$('div.mystuff img').attr('src','images/'+curImage);
}, 1000);
You can use the setTimeout function to call a predefined function to change your images like this:
var changeImage = function (){
<code>
};
var t = setTimeout(changeImage, <time in milliseconds>);
Make sure you are not calling setTimeout(changeImage(), <time in milliseconds>); (note the two parentheses)
This is to be avoided and you should try to use a function instead of a string to be evaluated as the first parameter to setTimeout().
Alternatively, you could use an anonymous function instead of creating changeImage.
Ex.
var t = setTimeout(function() { <code>}, <time in milliseconds>);

Categories

Resources