Hide element with a delay - javascript

In this case the element hides at ones. Can't understand why it's not show a "P" tag at first and then slowly hides it. Please, help me to fix a problem.
var step = 0.1;
var delay = 90000;
var displayMe = function() {
if (element.style.opacity < 1) {
element.style.opacity += step;
setTimeout('displayMe()', delay);
}
}
var hideMe = function() {
var elem = document.getElementById('regform');
if (elem.style.opacity >= 0) {
elem.style.opacity -= step;
setTimeout('hideMe ()', delay);
}
}
hideMe();
<p id="regform">aaaaaaaaaaaaaaaaa</p>

Element.style.prop will read only inline styles. Define style='opacity:1' for <p> element.
var step = 0.1;
var delay = 1000;
var displayMe = function() {
if (element.style.opacity < 1) {
element.style.opacity += step;
setTimeout(displayMe, delay);
}
}
var hideMe = function() {
var elem = document.getElementById('regform');
if (elem.style.opacity >= 0) {
elem.style.opacity -= step;
setTimeout(hideMe, delay);
}
}
hideMe();
<p id="regform" style='opacity:1'>aaaaaaaaaaaaaaaaa</p>

Try
document.getElementById('regform').style.opacity=1;
var hideMe = function()
{
var elem = document.getElementById('regform');
if(elem.style.opacity>0)
{
elem.style.opacity-= step;
setTimeout(hideMe, delay);
}
}
hideMe();
Fiddle

Try it with jquery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#regform').delay(1000).fadeOut(2000);
});
</script>
<p id="regform" style='opacity:1'>aaaaaaaaaaaaaaaaa</p>
Documentation .fadeOut()

Related

Pause autonomous function if user interacts?

I'm trying to make a carousel that runs automatically, but if a user interacts with the controls I want the carousel to reset its timer.
What ive built works to an extent, but if you interact with the control-dot the timer isnt reset so it throws some funny results...
Here's my JS
/* Js for carousel */
$('.steps__step-1').addClass('active');
$(function() {
var lis = $('.step'),
currentHighlight = 0;
N = 5; // Duration in seconds
setInterval(function() {
currentHighlight = (currentHighlight + 1) % lis.length;
lis.removeClass('active').eq(currentHighlight).addClass('active');
}, N * 1000);
});
$('.control-dot').on('click', function(e) {
e.preventDefault();
$('.active').removeClass('active');
var itemNo = $(this).index() - 1;
$('.step').eq(itemNo).addClass('active');
});
http://jsfiddle.net/tnzLha3o/1/
You should store interval id in a variable (let intervalId = setInterval(...)) and then use it to restart it.
Here is your updated fiddle: http://jsfiddle.net/gudzdanil/uzoydp6a/2/
So that your code will look like:
var duration = 5;
var lis = $('.step'),
currentHighlight = 0;
var intervalId = null;
$(function() {
$('.steps__step-1').addClass('active');
runCarousel();
});
$('.control-dot').on('click', function(e) {
e.preventDefault();
$('.active').removeClass('active');
var itemNo = $(this).index() - 1;
$('.step').eq(itemNo).addClass('active');
rerunCarousel();
});
function rerunCarousel() {
if(intervalId) clearInterval(intervalId);
intervalId = null;
runCarousel();
}
function runCarousel() {
intervalId = setInterval(function() {
currentHighlight = (currentHighlight + 1) % lis.length;
lis.removeClass('active').eq(currentHighlight).addClass('active');
}, N * 1000)
}
Add a variable to stop it.
var stop = false
$('.steps__step-1').addClass('active');
$(function() {
var lis = $('.step'),
currentHighlight = 0;
N = 5; // Duration in seconds
setInterval(function() {
if (!stop) {
currentHighlight = (currentHighlight + 1) % lis.length;
lis.removeClass('active').eq(currentHighlight).addClass('active');
}
}, N * 1000);
});
$('.control-dot').on('click', function(e){
e.preventDefault();
$('.active').removeClass('active');
var itemNo = $(this).index() - 1;
$('.step').eq(itemNo).addClass('active');
stop = !stop
});
http://jsfiddle.net/quvgxz63/

How to create a countdown timer before a function is performed

What I want to do is have a coin flip which will start a countdown when the flip button is pressed or if instructed to elsewhere. Then I want it to countdown 3, 2, 1 and display that on the screen. When the countdown is complete it will display heads or tails. The reason for this is so I do not have to create an animation of the coin flipping instead a delay to build the tension.
This is the code I have so far:
<html>
<head>
<title>Coin Toss </title>
<script>
function toss() {
if (Math.random()>.5) {
window.document.coin.src = "CT.jpg";
}
else {
window.document.coin.src = "T.jpg";
}
return false;
}
</script>
</head>
<body>
<img name="coin" src="questionmark.png">
<form action="" onSubmit="return toss();">
<input type="submit" value="TOSS">
</form>
</body>
</html>
Here's an example using setTimeout. In this instance I've removed the form as you don't strictly need it imo, and used event listeners so that the JS call is removed from the HTML.
HTML
<img id="coin"/><br/>
<button id="toss">Toss</button><br/>
<div id="count"></div>
JS
function toss() {
var div = document.getElementById('coin');
if (Math.random() > .5) {
coin.src = "CT.jpg";
} else {
coin.src = "T.jpg";
}
}
function countDown() {
var count = 3, timer;
var div = document.getElementById('count');
// if count is not 0, add the new count to the
// count element and loop again, reducing the count number
// otherwise erase the count element, clear the timeout
// and run the toss function
var loop = function loop (count) {
if (count > 0) {
div.textContent = count--;
timer = setTimeout(loop, 1000, count);
} else {
div.textContent = '';
clearTimeout(timer);
toss();
}
}
// start the countdown
loop(count);
}
var button = document.getElementById('toss');
button.addEventListener('click', countDown, false);
DEMO
you can do this with a setInterval, here is an example:
Javascript:
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1932%20Type%201%20Silver%20Washington%20Quarter%20Obv.png">';
} else {
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1988%20Type%202%20Clad%20Washington%20Quarter%20Reverse.png">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
HTML:
<div id="toss"><div>
Also here is a Fiddle so you can test it out and see what it does:
http://jsfiddle.net/Cedriking/cLs9r3m6/
For your second question (in the comment), do this:
<html>
<head>
<title>This is my title</title>
</head>
<body>
<div id="toss"></div>
<script type="text/javascript">
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1932%20Type%201%20Silver%20Washington%20Quarter%20Obv.png">';
} else {
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1988%20Type%202%20Clad%20Washington%20Quarter%20Reverse.png">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
</script>
</body>
</html>

Text carousel on timer with fade in, fade out

I'm trying to have some text fade out, change, and fade back in at regular intervals and automatically (ie, no button).
I cannot get this code to synchronize setInterval with the fading. I've tried fadeToggle as well as a combination of fadeIn and fadeOut together.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="changeText">Zero</div>
<script type="text/javascript">
var text = ["One", "Two", "Three"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 3000);
function change() {
$("#changeText").fadeToggle(3000);
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}
</script>
PS I am agnostic about the solution. If this can be done more elegantly in CSS (which I've used for fading but not transition), please let me know.
Try utilizing .fadeTo() , remainder operator
var text = ["One", "Two", "Three"];
var counter = 0;
var elem = document.getElementById("changeText");
function change() {
$(elem).fadeTo(3000, 0, function() {
this.innerHTML = text[counter];
counter = ++counter % text.length;
$(this).fadeTo(3000, 1, change)
})
}
change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="changeText">Zero</div>
<script type="text/javascript">
</script>
There are a million ways to skin a cat. If you want to do fadeToggle, I wouldn't also use setInterval, because they will be called at the same time and cancel each other out.
One thing to keep in mind is that fadeToggle will effect more than just the opacity and turns the objects display off once it is hidden, and that could effect your layout.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div id="changeText">Zero</div>
<script type="text/javascript">
var text = ["One", "Two", "Three"];
var counter = 0;
var elem = document.getElementById("changeText");
$(document).ready(function(){ change()});
function change() {
$("#changeText").fadeToggle(3000, 'swing', function(){
if($("#changeText").css("display") == "none")
{
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}
change();
});
}
</script>
I'm not sure how this compares performance wise. This implementation has no dependencies.
(function() {
var STEP = 0.1;
var x = 0;
var text = ['one', 'two', 'three'];
var element = document.querySelector('#changeText');
if(!element) { return; }
element.innerText = text[0];
requestAnimationFrame(change);
function change() {
var y = Math.sin( x );
var opacity = (y + 1) / 2;
x += STEP;
element.style.opacity = opacity;
if(y <= -0.99 && Math.sin(x) > -0.99) {
var txtIdx = text.indexOf(element.innerText);
if(txtIdx === text.length - 1) {
element.innerText = text[0];
} else {
element.innerText = text[++txtIdx];
}
}
requestAnimationFrame(change);
}
})()

How to interchange between 2 logos?

I have the following code:
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
var images = new Array (logo1, logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
var images = new Array (logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
Its working well apart from the following bugs:
Image loads even though image already is showing on page.
I have an image onmousehover effect on that image and its causing bad effect.
Is it possible to interchange between the image src and the img onmousehover src?
Thanks
Alex
you can change the src of the img tag using JavaScript as below,
function hover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png');
}
function unhover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png');
}
and the html be
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
After Edit :
If you want to change it on some timeout, You need to put your below code inside window.onload = function() {}
var images = new Array();
images[0] = "logo_1.png";
images[1] = "logo_2.png";
var images = new Array();
for (var i = 0; i < 2; i++) {
images.push("logo_" + i + ".png");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if (x < 8) {
x += 1;
} else {
x = 0;
}
if (window.addEventListener) {
window.addEventListener('load', changeImg, false);
}
function changeImg() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
HTML:
<img id="ad" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png" />
Use jQuery hover to run code when hovering in or out of an element. Also use setTimeout to run code after a delay.
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
$(function() {
$('.logoimage').hover(function() {
setTimeout(function() {
$('.logoimage').attr('src', logo2);
}, 1000);
}, function() {
setTimeout(function() {
$('.logoimage').attr('src', logo1);
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logoimage" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png">

Jquery - Animate innerHTML possible?

I'm trying to have a function that does setTimeout, then changes the innerHTML:
<script type="text/javascript">
$(document).ready(function(){
setTimeout(function(){
document.getElementById("middlecolor").innerHTML='new text new text';
}, 1000);
});
</script>
Question: How could I animate the new text that appears, i.e. line by line as opposed to being written all at once?
Thanks for any suggestions!!
Try something like this:
<div id="text">
</div>
$(document).ready(function () {
var interval = setInterval(function () {
$('#text').append('<p style="display: none;">new text</p>');
$('#text p:last').fadeIn('slow');
}, 5000);
});
See the example here
If you want to kill the interval, can be doing this:
clearInterval(interval);
Greatings.
Line-by-line is a bit tricky, but possible.
var ps = document.getElementById("text").children;
var i = 0;
var $p = $(ps[i]);
setTimeout(function newline(){
$p.css("height", function(index, h){
h = parseInt(h);
h += parseInt($p.css("line-height"));
console.log(h, ps[i].scrollHeight);
if (h > ps[i].scrollHeight)
$p = $(ps[++i]);
return h;
});
if (i < ps.length)
setTimeout(newline, 200);
}, 200);​
I'd suggest to use a typewriter effect, which is also very likable: http://jsfiddle.net/pZb8W/1/
var ps = document.getElementById("text").children;
var i = 0;
var $p, text;
var speed = 20;
setTimeout(function newchar(){
if (!text) {
$p = $(ps[i++]);
text = $p.text();
$p.empty().show();
}
$p.append(document.createTextNode(text.charAt(0)));
text = text.slice(1);
if (text.length || i < ps.length)
setTimeout(newchar, Math.random()*speed+speed);
}, 3*speed);​
Here's a function that would animate in multiple lines of text, one after the other:
<script type="text/javascript">
$(document).ready(function(){
function animateAddText(id, text, delta) {
var lines = text.split("\n");
var lineCntr = 0;
var target = $("#" + id);
function addLine() {
if (lineCntr < lines.length) {
var nextLine = "";
if (lineCntr != 0) {
nextLine = "<br>";
}
nextLine += lines[lineCntr++];
$("<span>" + nextLine + "</span>").hide().appendTo(target).fadeIn(1000);
setTimeout(addLine, delta);
}
}
addLine();
}
var multilineText = "First line\nSecond Line\nThird Line\nFourth Line\nFifth Line";
animateAddText("middlecolor", multilineText, 1000);
});
</script>
And a working demo: http://jsfiddle.net/jfriend00/Gcg5T/

Categories

Resources