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/
Related
I would like to randomize characters on hover for a specific id.
It works fine on mouse enter but can't get it stop and back to initial text when mouse leave.
Here's the code.
jQuery(function($) {
function text_shuffle() {
"use strict";
var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var $_inter = setInterval(function() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}, 100);
}
$("#text-shuffle").mouseenter(text_shuffle);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
Thanks for your help
Use clearInterval to stop the randomize characters, replace the original text when mouse goes out of text.
jQuery(function($) {
function text_shuffle() {
"use strict";
var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$_inter = setInterval(function() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}, 100);
}
var value, $_inter;
$("#text-shuffle").mouseenter( function(){
value = $(this).html();
text_shuffle();
}).
mouseout(function(){
clearInterval($_inter);
$(this).html(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
You need to clear your interval on mouseleave. You haven't called a mouseleave function so your code scrambles the chars inside your div indefinitely.
All I've done was set the interval to a variable and clear the variable on mouseleave.
jQuery(function($) {
all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var int;
var counter = 0;
function textShuffle() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}
$("#text-shuffle").hover(function() {
int = setInterval(textShuffle, 100);
}, function () {
clearInterval(int);
document.getElementById("text-shuffle").innerText = "Home";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
(function(){
'use strict';
var all = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
elem = document.getElementById("text-shuffle"),
orig = elem.innerHTML;
var $_inter;
function text_shuffle()
{
var counter = 0;
$_inter = setInterval( function()
{
elem.innerHTML = elem.innerHTML.substring(0, counter) + all.charAt(( Math.random() * all.length ) | 0 ) + elem.innerHTML.substring(counter + 1);
counter = (counter+1) % elem.innerHTML.length;
}, 100);
}
function clear() { clearInterval( $_inter ); elem.innerHTML = orig };
$("#text-shuffle").hover( text_shuffle, clear )
}())
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()
I have a div with a next and previous button
<div class="b1"></div>
<input type="button" class="btnP" value="Prev"/>
<input type="button" class="btnN" value="Next"/>
and a list of css classes
.b1 { background-color:#fff;}
.b2 { background-color:#000;}
.b3 { background-color:#123;}
.b4 { background-color:#444;}
.b5 { background-color:#bbb;}
which i want to use for that div when the user press the next or previous button by that numbering order.
This is what i did so far:
http://jsfiddle.net/51dq5num/
var size_ini = 1;
$(".btnN").click(function () {
var size_increase = size_ini++;
var size_increase1 = size_ini;
$("#content").html("<span>" + size_increase + "</span>").removeClass().addClass("b" + size_increase);
if (size_increase > 4) {
size_ini = 1;
}
});
I manage to get the next button working but i'm not sure how to do it for the previous button
Is there a better way to do this rather then adding and removing css classes from the div?
Try this :
$(".btnP").click(function () {
var size_increase = $("#content").attr("class").substring(2, 1);
size_increase--;
if (size_increase < 1) {
size_increase = 5;
}
$("#content").html("<span>" + size_increase + "</span>").removeClass().addClass("b" + size_increase);
});
jsFiddle : http://jsfiddle.net/51dq5num/7/
You can do something like this:
var newClass = function(div, next) {
div[0].className = div[0].className.replace(/b\d+/, "b" + newClass[next ? 'next' : 'prev']());
};
newClass.atual = 1;
newClass.last = 5;
newClass.next = function(){
this.atual = (this.atual == this.last ? 1 : this.atual + 1);
return this.atual;
};
newClass.prev = function(){
this.atual = (this.atual == 1 ? this.last : this.atual - 1);
return this.atual;
};
var myDiv = $("#content");
$(".btnN").click(function () {
newClass(myDiv, true);
});
$(".btnP").click(function () {
newClass(myDiv, false);
});
Jsfiddle here.
This is a combined solution for both buttons.
var size_ini = 0;
$("input[type='button']").click(function () {
if($(this).hasClass("btnN"))
{
size_ini=size_ini+1;
var c="b"+size_ini;
$("#content").removeClass().addClass(c).html("TG"+size_ini);
}
else
{
size_ini=size_ini-1;
var c="b"+size_ini;
$("#content").removeClass().addClass(c).html("TG"+size_ini);
}
});
Note as it is not mentioned i have not checked on the max condition thus btnP can increase the counter infinitely.You can put it in a condn and limit it to a max value.
http://jsfiddle.net/n8dLgh3L/1/
Here is js code to increase and decrease.
var size_ini = 0;
$(".btnN").click(function () {
if (size_ini > 4) {
size_ini = 1;
} else {
size_ini++
}
$("#content").html("<span>" + size_ini + "</span>").removeClass().addClass("b" + size_ini);
});
$(".btnP").click(function () {
var size_decrease = $("#content").attr("class").substring(1, 2);
if (size_decrease <= 1) {
size_decrease = 5;
} else {
size_decrease--;
}
$("#content").html("<span>" + size_decrease + "</span>").removeClass().addClass("b" + size_decrease);
});
You ca achieve this with the help of .substr() for incrementing the number of class. Have a look.
function Getnumber(classNumber,nav)
{
var no=0;
if(nav=="P")
{
no=parseInt(classNumber.substr(1,2))-1;
}
else
{
no=parseInt(classNumber.substr(1,2))+1;
}
return no;
}
$(".btnN").on("click",function(){
var oldClass=$('div').attr("class");
var num=Getnumber(oldClass,"N");
if(num<6)
$('div').addClass("b"+num).removeClass(oldClass);
});
$(".btnP").on("click",function(){
var oldClass=$('div').attr("class");
var num=Getnumber(oldClass,"P");
if(num>0)
$('div').addClass("b"+num).removeClass(oldClass);
});
Feel free to ask.
I am attempting to create a responsive slider, that will change to a simple set of dot points when in mobile mode (< 940).
The issue I am facing is in my else statement I am unable to clearintervals that were made in the if statement, because t comes up as undefined. I have resorted to using
for (var i = 1; i < 99999; i++) window.clearInterval(i); to clear the interval which works, but I don't like it because it's ugly and cumbersome, is there another way of accomplishing this?
$(document).ready(function() {
function rePosition() {
//get responsive width
var container_width = $('.container').width();
//Slider for desktops only
if(container_width >= 940) {
//get variables
var slide_width = $('.slider_container').width();
var number_of_slides = $('.slider_container .slide').length;
var slider_width = slide_width*number_of_slides;
//set element dimensions
$('.slide').width(slide_width);
$('.slider').width(slider_width);
var n = 1;
var t = 0;
$('.slider_container').hover(function() {
clearInterval(t);
}, function() {
t = setInterval(sliderLoop,6000);
});
var marginSize = i = 1;
//Called in Doc Load
function sliderLoop(trans_speed) {
if (trans_speed) {
var trans_speed = trans_speed;
}
else
{
var trans_speed = 3000;
}
if (i < number_of_slides) {
marginSize = -(slide_width * i++);
}
else
{
marginSize = i = 1;
}
$('.slider').animate({ marginLeft: marginSize }, trans_speed);
}
t = setInterval(sliderLoop,6000);
$('.items li').hover(function() {
$('.slider').stop();
clearInterval(t);
var item_numb = $(this).index();
i = item_numb;
sliderLoop(500);
}, function() {
t = setInterval(sliderLoop,6000);
});
}
else
{
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
$('.slider').stop(true, true);
$('.slider').css('margin-left', '0px');
//rearrange content
if($('.slider .slide .slide_title').length < 1) {
$('.items ul li').each(function() {
var item_numb = $(this).index();
var content = $(this).text();
$('.slider .slide:eq(' + item_numb + ')').prepend('<div class="title slide_title">' + content + '</div>')
});
}
}
}
rePosition();
$(window).resize(function() {
rePosition();
});
});
Teemu's comment is correct. I'll expand on it. Make an array available to all of the relevant code (just remember that globals are bad).
$(document).ready(function() {
var myIntervalArray = [];
Now, whenever you create an interval you will need to reference later, do this:
var t = setInterval();//etc
myIntervalArray.push(t); //or just put the interval directly in.
Then to clear them, just loop the array and clear each interval.
for (var i=0; i<myIntervalArray.length; i++)
clearInterval(myIntervalArray[i]);
}
Umm, wouldn't t only be defined when the if part ran... as far as I can tell, this is going to run and be done... the scope will be destroyed. If you need to maintain the scope across calls, you'll need to move your var statements outside of reposition(), like so:
$(document).ready(function() {
var t = 0;
...
function rePosition() { ... }
});
I have an element with animated top margin. I need to detect if it isn't too close from the border, and if it is, scroll parent div to lower position, to prevent animated element from hiding. Here is an example:
http://jsfiddle.net/zYYBR/5/
This green box shouldn't be below the red line after clicking the "down" button.
Do you mean this?
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down').click(function() {
var goStep = step;
var elHeight = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
if((elHeight + step) > limit)
{
goStep = limit - elHeight;
}
new_margin = goStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({marginTop: new_margin}, 1000);
});
http://jsfiddle.net/zYYBR/8/
EDIT: Or maybe something like that (of course you can improve the calculation, because currently it's very buggy with scroll):
var new_margin;
var step = 75;
$('#down').click(function () {
scroll(1000);
});
var scrollTimer = null;
$("#container").bind("scroll", function () {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function () { scroll(1); }, 10);
});
function scroll(speed) {
var scrollStep, animationStep = step;
var currentBoxBottom = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;
var nextCurrentBoxBottom = currentBoxBottom + step;
var limit = $("#max")[0].offsetTop + $("#container")[0].scrollTop;
if (nextCurrentBoxBottom > limit) {
if (limit >= $("#container")[0].scrollTop) {
scrollStep = $("#container")[0].scrollTop + nextCurrentBoxBottom - limit;
}
else {
scrollStep = $("#container")[0].scrollTop - nextCurrentBoxBottom - limit;
animationStep = nextCurrentBoxBottom - limit;
}
$("#container")[0].scrollTop = scrollStep;
}
new_margin = animationStep + parseInt($('#animated').css('margin-top'));
$("#animated").animate({ marginTop: new_margin }, speed);
}
http://jsfiddle.net/zYYBR/13/
Do you mean something like this?
I have the same visual result as Alex Dn did, but I added a little extra direction to what I think you're talking about. If it's what you're looking for I'll make updates:
var new_margin;
var step = 75;
var limit = $("#max")[0].offsetTop;
$('#down2').click(function() {
var anim = $("#animated");
var hrOff = $("#max").offset();
var thOff = anim.offset();
new_margin = Math.min(hrOff.top - thOff.top - anim.height(), 75);
console.log(new_margin, hrOff.top, thOff.top);
var st = 0;
if (new_margin < 75) {
st = 75 - new_margin;
//have container scroll by this much?
}
anim.animate({
marginTop: "+=" + new_margin
}, 1000);
});
http://jsfiddle.net/zYYBR/10/