Fade in Animations - javascript

So. I've been trying to create a simple piece of text that fades in when the page loads. I've explored a lot hear on Stack Overflow and also considered this:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_fadein
I even looked into using a window.onload, not to mention this:
<body onload="$("#fadein p.desktoptheme").delay(1000).animate({"opacity": "1"}, 700);">
But the fade in won't work. The text never displays.
I have the opacity for the element set as 0 (using CSS).
<script type="text/javascript">
$("#fadein p.desktoptheme").delay(1000).animate({"opacity": "1"}, 700);
</script>
One moar thing: The text that's placed inside the <p class="desktoptheme"></p> tag is generated with PHP. It could be that PHP is server-side while JavaSciprt is client-side. If so, what do I use? A delay? AJAX?
Any thoughts?

When using jQuery you will always want to put your DOM manipulating code inside jQuery´s .ready(function()), or else your code will fire before the page was successfully loaded
Example:
<script type="text/javascript">
$( document ).ready(function() {
$("#fadein p.desktoptheme").delay(1000).animate({"opacity": "1"}, 700);
});
</script>
For a more elegant solution, you may also consider using CSS animations do get the same effect.
Check out this link for more information on fading in elements with CSS.
To place server-side content in a page rendered with PHP, provided your text is available before the page is loaded, you just need to echo the variable mixed with your HTML.
Example:
<p class="desktoptheme"><?php echo "Hello world"; ?></p>

Any text that you stick inside of your element with PHP will already be there when javascript runs--as you said, PHP is server side, javascript is client side. So you don't need to worry about that.
I see you're using jQuery, so you should be looking at $(document).ready(). This function executes some javascript after the page has finished loading. For example:
JS:
$(document).ready(function() {
$('.fadein').animate({'opacity' : 1}, 700);
})
HTML:
<p class='fadein'>
This is some text that will fade in.
</p>
CSS:
.fadein {
opacity: 0;
}
Here's a JSFiddle so you can play around with it some more. Notice that the class of the paragraph (fadein) has to match your jQuery selector $('.fadein') and your css selector .fadein.
Fiddle

I have a function which does just that. It looks a bit like a jQuery fade(), but it's bog-standard JavaScript and can be used with or without an on-completion callback function.
/* fade.In(), fade.Out():
el = element object
dur = duration milliseconds
fn = callback function
*/
var fade = {
In: function(el, dur, fn) {
var time = Math.round(dur / 10);
function fader(t, e, v) {
if (v < 1) {
e.style.opacity = v;
setTimeout(function () {
fader(t, e, parseFloat((v += 0.1).toFixed(2)));
}, t);
} else {
e.style.opacity = '1';
if (fn) fn();
}
}
if (el.style.display === 'none') el.style.display = 'block';
el.style.opacity = '0';
fader(time, el, 0);
},
Out: function(el, dur, fn) {
var time = Math.round(dur / 10);
function fader(t, e, v) {
if (v > 0) {
e.style.opacity = v;
setTimeout(function () {
fader(t, e, parseFloat((v -= 0.1).toFixed(2)));
}, t);
} else {
el.style.opacity = '0';
e.style.display = 'none';
if (fn) fn();
}
};
fader(time, el, 1);
}
};
/* Usage */
var elem1 = document.getElementById('id1');
var elem2 = document.getElementById('id2');
// fade in with callback
fade.In(elem1, 500, function() {
// ... do something after fade in ...
});
// fade out without callback
fade.Out(elem2, 666);
Works best for relatively fast transitions: c.500ms +|- 200 (ish).
For you purposes just call the fade.In() function on the chosen element on page load.
Hope that helped. :)

Check out animate.css. Put this in your head:
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.css">
Then add
animated fadeIn
to your class:
<p class="desktoptheme animated fadeIn"></p>
If you want it to animate when you scroll to the element check out WOW.js

I would highly recommend using a js library called velocity to help with css animations.
If I follow you right, it would look something like this...
css
p.desktoptheme {
display: none;
opacity: none;
}
jquery
$(function(){
$('p.desktoptheme').velocity('fadeIn', {
'duration': 300,
'delay': 1000,
'complete': function(){
// all done!
}
});
});

Related

Alternate content of a div every 3 seconds with javascript

I would like to alternate the contents of a div (or swap in a new div if better) every few seconds, with a fade in/out. Jquery prefered, or pure js fine too.
Based on Arun's solution, I have added the Jquery below, and it works perfectly... but how do I make it repeat?
HTML:
<div class="wrapper" style="height:100px">
<div id="quote1">I am a quote</div>
<div id="quote2">I am another quote</div>
<div id="quote3">I am yet another quote</div>
</div>
Javascript: (as per Arun in the comments)
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
$els.eq(++i % len).fadeIn();
})
}, 2500)
})
Try
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
Demo: Fiddle
Here is a working example:
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
this sounds like a job for...a slider. There are a ton of jQuery plugin options out there,
I've always been a fan of Malsup
jQuery plugins by malsup
he even has responsive ones ready to go. Google "jQuery slider" to be overwhelmed with options.
Use a slider plugin there are lots on the internet. This is a simple snippet I wrote that works with any number of elements without having to change the javascript.
It's very easy to change.
http://jsfiddle.net/Ux9cD/39/
var count = 0;
$('.wrapper div').css('opacity', '0');
var varName = setInterval(function() {
//hide all the divs or set opacity to 0
$('.wrapper div').css('opacity', '0');
//get length
var length = $('.wrapper div').length;
//get first child:
var start = $('.wrapper div').eq(count);
if (count < length) {
animateThis(start,length,count);
count++;
} else {
console.log('end of list');
//restore back to hidden
//set count back to 0
$('.wrapper div').css('opacity', '0');
count = 0;
}
}, 2000);
varName;
function animateThis(start,length,count)
{
$( start ).animate({
opacity: 1
}, 1000, "linear", function() {
//return count++;
});
}
This will do it if you set your second and third divs to hidden:
window.setInterval(function(){
window.setTimeout(function(){
$('#quote1').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 0);
window.setTimeout(function(){
$('#quote2').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 3000);
window.setTimeout(function(){
$('#quote3').fadeIn('slow').delay(3000).fadeOut('fast').delay(6000);
}, 6000);
}, 3000);
It's not going to do exactly what you want because fading takes time, so two divs will be onscreen at the same time. I tried to remedy this by having them fadeIn() slowly and fadeOut() quickly, but I'd recommend taking out the fading altogether and just hiding them.
See demo.
Also, #ArunPJohny has a solution here that is a bit difficult to understand but does get rid of the fading delay problem. Alternatively, here's my no-fading solution.
HTML
<div id="div1">quote 1</div>
<div id="div2" style="display:none">quote 2</div>
JavaScript
i=0;
setInterval(function(){
if(i%2 == 0)
$('#div1').fadeOut('slow', function(){
$('#div2').fadeIn('slow')
})
else
$('#div2').fadeOut('slow', function(){
$('#div1').fadeIn('slow')
})
i++;
}, 2000)
Fiddle
Here is something you can try if you can do without fade in and fadeout. Just a simple few lines of java script no need to add any plugins etc.
Also look at this link Jquery delay it has sample with delay and fade in fadeout. May be you can tailor it to your needs.
Try in your browser
<html>
<head>
<script type="text/javascript">
function swapDiv(){
var firstString = document.getElementById("quote1").innerHTML;
var secondString = document.getElementById("quote2").innerHTML;
document.getElementById("quote1").innerHTML = secondString;
document.getElementById("quote2").innerHTML = firstString;
setTimeout(swapDiv, 3000);
}
setTimeout(swapDiv, 3000);
</script>
</head>
<body>
<div id="quote1">I am another quote</div><span>
<div id="quote2">I am yet another quote</div><span>
</body>
</html>

faking a Gif with javascript/jquery

I have a function that hides and shows divs on scroll based on pageY position, but I also need the ability to have it automatically hide and show divs in order(only the ones with children), sort of like a fake animated Gif, looping forever.
I tried this:
function autoPlay() {
$('.conP').each(function(){
if ($(this).children().length > 0) {
setInterval(function(){
$(this).show().delay('100').hide();
},300);
}
});
}
which is not returning any errors, but it's not hiding or showing any of the divs with class="conP".
Any suggestions as to what I'm doing wrong/how I could improve this?
try this -
function autoPlay() {
$('.conP').each(function(){
if ($(this).children().length > 0) {
var $that = $(this);
setInterval(function(){
$that.show().delay('100').hide();
},300);
}
});
}
You have an incorrect reference to this in your setInterval closure. Refer to "How this works" in JavaScript Garden.
In your case you should save the reference to this in a variable:
$('.conP').each(function() {
var $element = $(this);
setInterval(function () {
$(element).show().delay('100').hide();
}, 300);
});
Or, better use the first argument passed to each, which is equal to $(this) in this case.
Not sure it's a great idea to run intervals inside loops, but I'm guessing the issue is scope inside the interval function :
function autoPlay() {
$('.conP').each(function(i, elem){
if ( $(elem).children().length ) {
setInterval(function(){
$(elem).show().delay(100).hide();
},300);
}
});
}
I really appreciate all the help guys, I seem to have figured out the animation part:
setInterval( function() {
autoPlay();
},120);
function autoPlay() {
var backImg = $('#outterLax div:first');
backImg.hide();
backImg.remove();
$('#outterLax').append(backImg);
backImg.show();
}
By hiding whichever div is first, and removing it from-then appending it back into-the containing div, and showing the new first div, it animates quite nicely!

jQuery Animations Control Sequence

I'm am attempting to build a homepage that has animations. I am having hard time controlling my animations though. All I need is to hide elements, and then show elements after a certain time. Loop through that sequence, and pause and show all elements when the someone hovers over the box. Example simple animation.
I have a long way to go. At first I tried using the .css() visibility property, now I'm using .show() and .hide().
I need a way to loop through my animations. I attempt to add another
setTimeout(clear1(), 3000);
to the end of my box1 function, but that wouldn't work for some reason.
I need a way to on a user hover over #box1, that all animations stop. I have tried using .clearQueue, but I couldn't get that to work.
First of all, set to your css:
.box {display: none;}
SHOW ALL BOXES ON HOVER See Demo
This will show all boxes on hover and then continue the animation from where it stopped (will hide the boxes that hadn't shown up during the animation). I think that is what you are after.
var index = 0; // To keep track of the last div showed during animation
var time_of_delay = 1000; // Set the time of delay
// Start the animation
$(document).ready(function () {
box1(time_of_delay);
});
// The hover states
$("#box1_1").hover(
function() {
box1(0);
}, function() {
box1(time_of_delay);
});
// The animation function
function box1 (delay_time) {
var time=delay_time;
if(time>0) {
$(".box").slice(index).each(function() {
$(this).hide().delay(time).show(0);
time=time+time_of_delay;
});
index=0;
} else {
$(".box:visible").each(function() {
index++;
});
$(".box").stop(true).show(0);
}
}
PAUSE ON HOVER See Demo
This will only pause the animation and continue from where it stopped.
var time_of_delay = 1000; // Set the time of delay
// Start the animation
$(document).ready(function () {
box1(time_of_delay);
});
// The hover states
$("#box1_1").hover(
function() {
box1(0);
}, function() {
box1(time_of_delay);
});
// The animation function
function box1 (delay_time) {
var time=delay_time;
if(time>0) {
$(".box:hidden").each(function() {
$(this).delay(time).show(0);
time=time+time_of_delay;
});
} else {
$(".box").stop(true);
}
}
I used setTimeout and clearTimeout and periodically call a function that increments (and resets) the box to display. Since I assign setTimout to boxt, I am able to call clearTimeout(boxt) on box1's hover event so that I can stop specifically that loop. Here's my jsfiddle. It might not be the exact effect you're trying to achieve, but it should be the right functionality and be easily adaptable with a few tweaks. Let me know if this works for you and if you have any questions about how it works :)
LIVE DEMO
var $box = $('#box1').find('.box'),
boxN = $box.length,
c = 0,
intv;
$box.eq(c).show(); // Show initially the '0' indexed .box (first one)
function loop(){
intv = setInterval(function(){
$box.eq(++c%boxN).fadeTo(400,1).siblings().fadeTo(400,0);
},1000);
}
loop(); // Start your loop
$('#box1').on('mouseenter mouseleave', function( e ){
return e.type=='mouseenter' ? (clearInterval(intv))($box.fadeTo(400,1)) : loop();
});
Where ++c%boxN will take care to loop your animation using the Modulo % (reminder) operator inside a setInterval. Than all you need to do is to register a mouseenter and mouseleave on the parent element to:
clear the Interval on mouseenter + fade all your elements
restart your loop function on mouseleave.
Here's one way to do it:
// hide all of the boxes
$('.box').hide();
// reference to each box, the current box in this list and a flag to stop the animation
var divs = box1.getElementsByClassName('box');
var i = 0;
var run = true;
// this will animate each box one after the other
function fade(){
if(i < divs.length && run){
$(divs[i++]).fadeIn(500, function(){
setTimeout(fade, 1000);
});
}
};
fade();
// stop the above function from running when the mouse enters `box1`
$('#box1').on('mouseenter', function(){console.log('enter');
run = false;
});
// start the function again from where we stopped it when the mouse leaves `box1`
$('#box1').on('mouseleave', function(){console.log('leave');
run = true;
fade();
});
Demo: http://jsfiddle.net/louisbros/dKcn5/

Text blinking jQuery

What is an easy way to make text blinking in jQuery and a way to stop it? Must work for IE, FF and Chrome. Thanks
A plugin to blink some text sounds a bit like overkill to me...
Try this...
$('.blink').each(function() {
var elem = $(this);
setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
} else {
elem.css('visibility', 'hidden');
}
}, 500);
});
Try using this blink plugin
For Example
$('.blink').blink(); // default is 500ms blink interval.
//$('.blink').blink(100); // causes a 100ms blink interval.
It is also a very simple plugin, and you could probably extend it to stop the animation and start it on demand.
here's blinking with animation:
$(".blink").animate({opacity:0},200,"linear",function(){
$(this).animate({opacity:1},200);
});
just give a blink class whatever u want to blink:
<div class="someclass blink">some text</div>
all regards to DannyZB on #jquery
features:
doesn't need any plugins (but JQuery itself)
does the thing
If you'd rather not use jQuery, this can be achieved with CSS3
#-webkit-keyframes blink {
from { opacity: 1.0; }
to { opacity: 0.0; }
}
blink {
-webkit-animation-name: blink;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: cubic-bezier(1.0,0,0,1.0);
-webkit-animation-duration: 1s;
}
Seems to work in Chrome, though I thought I heard a slight sobbing noise.
Combine the codes above, I think this is a good solution.
function blink(selector){
$(selector).animate({opacity:0}, 50, "linear", function(){
$(this).delay(800);
$(this).animate({opacity:1}, 50, function(){
blink(this);
});
$(this).delay(800);
});
}
At least it works on my web.
http://140.138.168.123/2y78%202782
Here's mine ; it gives you control over the 3 parameters that matter:
the fade in speed
the fade out speed
the repeat speed
.
setInterval(function() {
$('.blink').fadeIn(300).fadeOut(500);
}, 1000);
You can also use the standard CSS way (no need for JQuery plugin, but compatible with all browsers):
// Start blinking
$(".myblink").css("text-decoration", "blink");
// Stop blinking
$(".myblink").css("text-decoration", "none");
W3C Link
This is the EASIEST way (and with the least coding):
setInterval(function() {
$( ".blink" ).fadeToggle();
}, 500);
Fiddle
Now, if you are looking for something more sophisticated...
//Blink settings
var blink = {
obj: $(".blink"),
timeout: 15000,
speed: 1000
};
//Start function
blink.fn = setInterval(function () {
blink.obj.fadeToggle(blink.speed);
}, blink.speed + 1);
//Ends blinking, after 'blink.timeout' millisecons
setTimeout(function () {
clearInterval(blink.fn);
//Ensure that the element is always visible
blink.obj.fadeIn(blink.speed);
blink = null;
}, blink.timeout);
Fiddle
You can also try these:
<div>some <span class="blink">text</span> are <span class="blink">blinking</span></div>
<button onclick="startBlink()">blink</button>
<button onclick="stopBlink()">no blink</button>
<script>
function startBlink(){
window.blinker = setInterval(function(){
if(window.blink){
$('.blink').css('color','blue');
window.blink=false;
}
else{
$('.blink').css('color','white');
window.blink = true;
}
},500);
}
function stopBlink(){
if(window.blinker) clearInterval(window.blinker);
}
</script>
$.fn.blink = function(times, duration) {
times = times || 2;
while (times--) {
this.fadeTo(duration, 0).fadeTo(duration, 1);
}
return this;
};
Here you can find a jQuery blink plugin with its quick demo.
Basic blinking (unlimited blinking, blink period ~1 sec):
$('selector').blink();
On a more advanced usage, you can override any of the settings:
$('selector').blink({
maxBlinks: 60,
blinkPeriod: 1000, // in milliseconds
onBlink: function(){},
onMaxBlinks: function(){}
});
There you can specify the max number of blinks as well as have access to a couple of callbacks: onBlink and onMaxBlinks that are pretty self explanatory.
Works in IE 7 & 8, Chrome, Firefox, Safari and probably in IE 6 and Opera (although haven't tested on them).
(In full disclosure: I'm am the creator of this previous one. We had the legitimate need to use it at work [I know we all like to say this :-)] for an alarm within a system and I thought of sharing only for use on a legitimate need ;-)).
Here is another list of jQuery blink plugins.
this code is work for me
$(document).ready(function () {
setInterval(function(){
$(".blink").fadeOut(function () {
$(this).fadeIn();
});
} ,100)
});
You can try the jQuery UI Pulsate effect:
http://docs.jquery.com/UI/Effects/Pulsate
Easiest way:
$(".element").fadeTo(250, 0).fadeTo(250,1).fadeTo(250,0).fadeTo(250,1);
You can repeat this as much as you want or you can use it inside a loop. the first parameter of the fadeTo() is the duration for the fade to take effect, and the second parameter is the opacity.
$(".myblink").css("text-decoration", "blink");
do not work with IE 7 & Safari. Work well with Firefox
This stand-alone solution will blink the text a specified number of times and then stop.
The blinking uses opacity, rather than show/hide, fade or toggle so that the DIV remains clickable, in case that's ever an issue (allows you to make buttons with blinking text).
jsFiddle here (contains additional comments)
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var init = 0;
$('#clignotant').click(function() {
if (init==0) {
init++;
blink(this, 800, 4);
}else{
alert('Not document.load, so process the click event');
}
});
function blink(selector, blink_speed, iterations, counter){
counter = counter | 0;
$(selector).animate({opacity:0}, 50, "linear", function(){
$(this).delay(blink_speed);
$(this).animate({opacity:1}, 50, function(){
counter++;
if (iterations == -1) {
blink(this, blink_speed, iterations, counter);
}else if (counter >= iterations) {
return false;
}else{
blink(this, blink_speed, iterations, counter);
}
});
$(this).delay(blink_speed);
});
}
//This line must come *AFTER* the $('#clignotant').click() function !!
window.load($('#clignotant').trigger('click'));
}); //END $(document).ready()
</script>
</head>
<body>
<div id="clignotant" style="background-color:#FF6666;width:500px;
height:100px;text-align:center;">
<br>
Usage: blink(selector, blink_speed, iterations) <br />
<span style="font-weight:bold;color:blue;">if iterations == -1 blink forever</span><br />
Note: fn call intentionally missing 4th param
</div>
</body>
</html>
Sources:
Danny Gimenez
Moses Christian
Link to author
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<div id="msg"> <strong><font color="red">Awesome Gallery By Anil Labs</font></strong></p> </div>
<script type="text/javascript" >
function blink(selector){
$(selector).fadeOut('slow', function(){
$(this).fadeIn('slow', function(){
blink(this);
});
});
}
blink('#msg');
</script>
I was going to post the steps-timed polyfill, but then I remembered that I really don’t want to ever see this effect, so…
function blink(element, interval) {
var visible = true;
setInterval(function() {
visible = !visible;
element.style.visibility = visible ? "visible" : "hidden";
}, interval || 1000);
}
I feel the following is of greater clarity and customization than other answers.
var element_to_blink=$('#id_of_element_to_blink');
var min_opacity=0.2;
var max_opacity=1.0;
var blink_duration=2000;
var blink_quantity=10;
var current_blink_number=0;
while(current_blink_number<blink_quantity){
element_to_blink.animate({opacity:min_opacity},(blink_duration/2),"linear");
element_to_blink.animate({opacity:max_opacity},(blink_duration/2),"linear");
current_blink_number+=1;
}
This code will effectively make the element(s) blink without touching the layout (like fadeIn().fadeOut() will do) by just acting on the opacity ; There you go, blinking text ; usable for both good and evil :)
setInterval(function() {
$('.blink').animate({ opacity: 1 }, 400).animate({ opacity: 0 }, 600);
}, 800);
Blinking !
var counter = 5; // Blinking the link 5 times
var $help = $('div.help');
var blinkHelp = function() {
($help.is(':visible') ? $help.fadeOut(250) : $help.fadeIn(250));
counter--;
if (counter >= 0) setTimeout(blinkHelp, 500);
};
blinkHelp();
This code might help to this topic. Simple, yet useful.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval("$('#myID/.myClass').toggle();",500);
});
</script>
I like alex's answer, so this is a bit of an extension of that without an interval (since you would need to clear that interval eventually and know when you want a button to stop blinking. This is a solution where you pass in the jquery element, the ms you want for the blinking offset and the number of times you want the element to blink:
function blink ($element, ms, times) {
for (var i = 0; i < times; i++) {
window.setTimeout(function () {
if ($element.is(':visible')) {
$element.hide();
} else {
$element.show();
}
}, ms * (times + 1));
}
}
Some of these answers are quite complicated, this is a bit easier:
$.fn.blink = function(time) {
var time = typeof time == 'undefined' ? 200 : time;
this.hide(0).delay(time).show(0);
}
$('#msg').blink();
Seeing the number of views on this question, and the lack of answers that cover both blinking and stopping it, here goes: try jQuery.blinker out (demo).
HTML:
<p>Hello there!</p>
JavaScript:
var p = $("p");
p.blinker();
p.bind({
// pause blinking on mouseenter
mouseenter: function(){
$(this).data("blinker").pause();
},
// resume blinking on mouseleave
mouseleave: function(){
$(this).data("blinker").blinkagain();
}
});
Indeed a plugin for a simple blink effect is overkill. So after experimenting with various solutions, I have choosen between one line of javascript and a CSS class that controls exactly how I want to blink the elements (in my case for the blink to work I only need to change the background to transparent, so that the text is still visible):
JS:
$(document).ready(function () {
setInterval(function () { $(".blink").toggleClass("no-bg"); }, 1000);
});
CSS:
span.no-bg {
background-color: transparent;
}
Full example at this js fiddle.
Blink functionality can be implemented by plain javascript, no requirement for jquery plugin or even jquery.
This will work in all the browsers, as it is using the basic functionality
Here is the code
HTML:
<p id="blinkThis">This will blink</p>
JS Code:
var ele = document.getElementById('blinkThis');
setInterval(function () {
ele.style.display = (ele.style.display == 'block' ? 'none' : 'block');
}, 500);
and a working fiddle
This is what ended up working best for me. I used jQuery fadeTo because this is on WordPress, which already links jQuery in. Otherwise, I probably would have opted for something with pure JavaScript before adding another http request for a plugin.
$(document).ready(function() {
// One "blink" takes 1.5s
setInterval(function(){
// Immediately fade to opacity: 0 in 0ms
$(".cursor").fadeTo( 0, 0);
// Wait .75sec then fade to opacity: 1 in 0ms
setTimeout(function(){
$(".cursor").fadeTo( 0, 1);
}, 750);
}, 1500);
});
I have written a simple jquery extension for text blink whilst specifying number of times it should blink the text, Hope it helps others.
//add Blink function to jquery
jQuery.fn.extend({
Blink: function (i) {
var c = i; if (i===-1 || c-- > 0) $(this).fadeTo("slow", 0.1, function () { $(this).fadeTo("slow", 1, function () { $(this).Blink(c); }); });
}
});
//Use it like this
$(".mytext").Blink(2); //Where 2 denotes number of time it should blink.
//For continuous blink use -1
$(".mytext").Blink(-1);
Text Blinking start and stop on button click -
<input type="button" id="btnclick" value="click" />
var intervalA;
var intervalB;
$(document).ready(function () {
$('#btnclick').click(function () {
blinkFont();
setTimeout(function () {
clearInterval(intervalA);
clearInterval(intervalB);
}, 5000);
});
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
intervalA = setTimeout("blinkFont()", 500);
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
intervalB = setTimeout("blinkFont()", 500);
}
</script>
<div id="blink" class="live-chat">
<span>This is blinking text and background</span>
</div>

jQuery slideshow

I'm trying to create my own slideshow. The following code fades from one image to another. I'd like to cycle from img1.jpg to img4.jpg but i'm not sure how to pause after each change.
i++;
temp = "img"+i+".jpg";
$("#img").fadeOut(function() {
$(this).load(function() { $(this).fadeIn(); });
$(this).attr("src", temp);
});
UPDATE: I've changed the code to the following. On John Boker's advice i've renamed the images to img0, img1, img2, img3. It goes to the first, second, third image the just stops. Any ideas?
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var temp="";
function slideshow(i)
{
temp = "img"+i+".jpg";
$("#img").fadeOut(function() {
$(this).load(function() {
$(this).fadeIn();
// set a timeout of 5 seconds to show the next image;
setTimeout(function(){ slideshow((i+1)%4); }, 5000);
});
$(this).attr("src", temp);
});
}
slideshow(0);
});
</script>
</head>
<body>
<img src="img1.jpg" id="img"/>
</body>
</html>
You can do it like this, using setInterval:
$(function() {
var i = 0;
// Four-second interval
setInterval(function() {
$("#img").fadeOut(function() {
$(this).attr("src", "img" + i++ % 4 + ".jpg");
$(this).fadeIn();
});
}, 4000);
}
I've simplified a few things that might have been causing some of the other problems you're seing, removing the (seemingly superfluous) call to load inside your fadeOut callback and eliminating the unnecessary temp variable.
(Finally, if you aren't just doing this to learn, consider using one of the many excellent slideshow plugins out there, like Cycle.)
you probably should have that inside a function:
// show image i
function slideshow(i)
{
temp = "img"+i+".jpg";
$("#img").fadeOut(function() {
$(this).load(function() {
$(this).fadeIn();
// set a timeout of 5 seconds to show the next image;
setTimeout(function(){ slideshow((i+1)%4); }, 5000);
});
$(this).attr("src", temp);
});
}
check out this example...
$(function(){
$('.slideshow img:gt(0)').hide();
setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000);
});
A fiddle
simply change the 4000 to 8000 in the script if you want to pause on each image for 8 seconds instead of 4 seconds.
Take a look at this jQuery slideshow question
set up window.setInterval(function, delay) to call a function at a set interval to execute the code that you have.
There are plenty of plugins that will already cycle images for you (unless the challenge is to write your own), one of my particular favourites is the cycle plugin.
One trick is use an animate a property of an element to its current value using a timer.
Eg
$("#img").fadeIn().show(3000).fadeOut();
Because $(this) is already visible, adding the .show(3000) means that element stays visible for 3s before fading out

Categories