animation like ning home page in jquery/JS/css? - javascript

how to create animation effect like ning home page (http://www.ning.com/) in jquery/JS/css? Iam talking about the curtain like animation for the text "Build and cultivate your own community of followers/fans/members/customers etc". Its a span element with class of "word"

You can create an array of words then loop through the array index with setInterval and use jQuery slideUp - slideDown for the animation.
html:
<p>Build and cultivate your own community of</p>
<div id="word">customers</div>
script:
var words = ['followers', 'fans', 'members', 'customers'];
var index = 0;//start with 0, first array index is 0
var $word = $('#word');
setInterval(function () {
if (index == words.length) {
//if current index is equal to the arrays length reset it to 0
index = 0;
}
//slideUp to hide
$word.slideUp(500, function () {
//on animation complete hidden change the text then slideDown to show
$word.text(words[index]).slideDown(500);
/*
It's always a good practice to separate increment/decrement
in a single line, as it might confuse some(especially new) programmers
*/
index++;
});
}, 2000);
See this jsfiddle.
You can use <span> but it will create a different effect because <span> is an inline element (check this jsfiddle). You need to set it to display:block to achieve the desired effects - jsfiddle demo.

Here's a solution. Made possible through the use of jQuery slideUp() and slideDown(). Additionally to allow for the animation to run every few seconds, I employed standard javascript setInterval().
HTML & JS
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<h1>Build something...</h1>
<h1 id="marqueeText">Testing</h1>
<button id="foo">Foo</button>
<script>
$(document).ready(function() {
// Drumroll, the main function that will start the rolling text.
var drumrollPlease = function() {
var index = 0;
var words = ['Awesome', 'Fun', 'Amazing'];
var marquee = $('#marqueeText');
// Key part here. This is the heart of the script, where your words will get rotated through,
// animating with slideup/slidedown and changing out your words based on the above words array.
window.setInterval(function () {
// Reset to the beginning once we reach end of our words list.
if (index >= words.length) {
index = 0;
}
// Set the marquee container to slide, update the word in our marquee container and then slide back down to reveal
// the new word.
marquee.slideUp('slow', function() {
marquee.html(words[index++]);
marquee.slideDown();
});
}, 2000); // Modify this duration in milliseconds as you please.
}
// I bound my button foo to illustrate how to trigger it. I could
// just as easily have called drumrollPlease() to have the function auto run
// when the document was in the ready state.
$('#foo').click(function() {
drumrollPlease();
});
});
</script>
</body>
</html>
See button activated plunker version: HERE
See automatic activated plunker version: HERE

You can use TweenlitMax
Includes
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.2/TweenMax.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.11.2/plugins/TextPlugin.min.js"></script>
HTML
<div>Build and cultivate your own community of</div>
<div id="compatibility">Followers</div>
Css:
#compatibility{
width:200px;
font-size:20px;
height:100px;
display:inline-block;
overflow:hidden;
position:absolute;
font-weight:bold;
}
JS:
$(document).ready(function(){
var tl = new TimelineLite({onComplete:onAnimationComplete});
text = $("#compatibility");
tl.fromTo(text,1,{height:0},{height:100})
.fromTo(text,1,{height:100},{height:0})
.set(text,{text:"fans"})
.fromTo(text,1,{height:0},{height:100})
.fromTo(text,1,{height:100},{height:0})
.set(text,{text:"members"})
.fromTo(text,1,{height:0},{height:100})
.fromTo(text,1,{height:100},{height:0});
function onAnimationComplete(){
tl.restart();
}
});
Check Fiddle

Related

CSS/JavaScript highlight text by changing color when text is changed

I have a JavaScript that updates a <p> html every couple of seconds based on the return value from an ajax call. I'd like to add a nice effect on the <p> so that whenever the html inside <p> changes, the background of the <p> changes to some other color for a second and then change back.
It is similar to how Yahoo Finance page shows the current price of a stock. - eg https://finance.yahoo.com/quote/BABA?p=BABA
How would I achieve something like this, preferably using CSS?
So far, I've tried the following.
<script>
setInterval(function () {
$("#bid").html(Math.random()).addClass('textColor').delay(1000).removeClass('textColor');
}, 1000);
</script>
And CSS
<style>
.textColor {
background-color: coral;
}
</style>
And HTML
<p id="bid"></p>
It looks like the effect is too fast, so the color change is not even visible.
https://jsfiddle.net/yn5gq1wd/1/
Update:
Here is the latest jsfiddle https://jsfiddle.net/yn5gq1wd/19/
Create a css class that has the background color you want to change it to.
When the html in the paragraph changes, add the css class to the paragraph and then use the setTimeout() method to remove the class after a set time (in milliseconds).
Here is an example of using setTimeout to add and remove the class on clicking the paragraph. You just need to replace the click event with some other event to fire the code.
<script>
$("#bid").click(function() {
$("#bid").addClass('textColor');
setTimeout(function() {
$("#bid").removeClass('textColor');
}, 1000);
})
</script>
Use MutationObserver:
const element = document.getElementById('spy-on-me');
setInterval(function () { // This is just to show how it works
element.innerHTML = element.innerHTML + element.innerHTML;
}, 3000);
const observer = new MutationObserver( function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type = 'childList') {
element.style.backgroundColor = 'lightgreen';
setTimeout(function () {
element.style.backgroundColor = 'white';
}, 200);
}
});
});
const config = { childList: true };
observer.observe(element, config);
<p id="spy-on-me">
some text
<p>
You can achieve this behavior in 3 steps:
1. create one css animation keyframe
#keyframes color-key-frame {
from {color: black;}
to {color: red;}
}
2. create one css class that is playing the animation ones
.color-animation {
animation-name: color-key-frame ;
animation-duration: 1s;
}
3. add the 'color-animation' class to the desired HTML node when your ajax call is finished
//inside your ajax callBack
var node = document.getElementById('idOfyourNode');
//remove prev adjusted class first
if(node.classList.contains('color-animation')){
node.classList.remove('color-animation');
}
//hack to skip one tick
setTimout(setTimeout(function(){
node.classList.add('color-animation');
},0);

Animate text change over time with JavaScript

I need to animate text change over time that never stops.
I've found this simple example with jquery:
$(function() {
$('#header-text-change').fadeOut(500, function() {
$(this).text('Some other text!').fadeIn(500);
});
});
Now I need to have more than one predefined text and that animation loops forever.
Thanks.
You can use setInterval() function to loop every N milliseconds.
Look this code snippet:
This example reset the index variable to 0 when hits TEXTS.length
var TEXTS = ["Some other text!", "Lord of the Rings", "Avengers", "Whatever text"];
var index = 0;
$(function() {
setInterval(function() {
$('#header-text-change').fadeOut(500, function() {
$(this).text(TEXTS[index++]).fadeIn(500);
if (index === TEXTS.length)
index = 0
});
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="header-text-change">
Hellow World!!
</h1>
See? now your code is looping, in this case every one second (1000ms).
function fadeout(){$('#header-text-change').fadeOut(undefined,changeText)}
function changeText(){
// implements your logic for changing the text
fadein();
}
function fadein(){$('#header-text-change').fadeIn(undefined,fadeout)}
You call fadeout and it loops using the callbacks( and they are named so you can reference them). Passing undefined as the first argument to fadeOut/fadeIn will use the default value of 400ms, you could change that by passing a variable that stores how long you want the animation to take.

How to rotate HTML content so that the order changes every 30 seconds with jQuery?

Basically i have created a single one column which holds 3 articles, i have given all the articles id's i.e news1,news2,news3 and added content to each accordingly [text and img,plus header]
What i am attempting to do is move the content of
article 1 to the location of article 2
article 2 to the location of article 3
article 3 to the location of article 1
with the articles changing location, every 30 seconds,[the above loop] i have tried appendTo,yesterday thought about fadeout, fadein, using a slide i persume would be; going a little over board in terms of code i think, then again on seconds thought..hmmm
i would rather change the content as one lot than, in parts, i.e headers, paragraphs, images etc.
this is how i started, the idea is if i can get it to work in one pair the rest would, straight forward, to do, be it copy and paste, with a edit of selectors.
setInterval(function(){
var x = getElementById("#news1");
(this).appendTo("#news3");
}, 30000);
Hopefully someone can steer me in the right direction, either by illustrating an example or an event 'action' to check out that might do the trick
Have you ever heard of the DOM manipulation, are those methods form Node reference https://developer.mozilla.org/en-US/docs/Web/API/Node that handles nodes like insertBefore, removeChild, appendChild an so on
For example the folowing uses standard dom manip. to shift the last element to first position in the tree stack. Read the comments for explanations:
// cache the container element
var containerEl = document.getElementById('container');
// This is a live reference to the child node finds the last child.
// The querySelector was use here in order to get a controll over
// what elements category should be manipulated
var lastEl = containerEl.querySelector('.article:last-child');
// move the element in front - remove from parent
containerEl.removeChild(lastEl);
// attach it back in the front.
containerEl.insertBefore(lastEl, containerEl.firstChild);
Now the second part of your problem is the timed event. you can use either requestAnimationFrame or a timer or a interval.
I personalty prefer the timer solution since is retro-compatible and it has no chance of executing the scheduled code simultaneous and you can stop the chaning internally without having a reference to the timerId. Maybe requestAnimationFrame is a better option, but that is up to you.
To chain schedule the executions a simple recursion does the trick:
var timerIdx;
var chainInterval = 6000; // in millis
var callback = function (){
// the execution code here;
timerIdx = setTimeout(callback, chainInterval);
};
to start it you just call :
callback();
to stop it you just call :
clearTimeout(timerIdx);
Now lets put everything together, the style is just for showcasing:
// cache the container element
var containerEl = document.getElementById('container');
var timerIdx;
var chainInterval = 1000; // in millis
var chainRotate = function (){
rotateChildElements(containerEl, '.article')
timerIdx = setTimeout(chainRotate, chainInterval);
};
var rotateChildElements = function(containerEl, childClassName){
// This is a live reference to the child node
var lastEl = containerEl.querySelector(childClassName+':last-child');
// move the element in front
containerEl.removeChild(lastEl);
containerEl.insertBefore(lastEl, containerEl.firstChild);
};
// Start
chainRotate();
var rotateBtn = document.getElementById('rotateBtn');
rotateBtn.addEventListener('click', function(ev){
if (timerIdx !== null){
ev.target.innerHTML = "Start Rotate";
clearTimeout(timerIdx);
timerIdx = null;
} else {
ev.target.innerHTML = "Stop Rotate";
chainRotate();
}
});
* {
box-sizing : border-box;
}
#container {
position: relative;
margin-left : auto;
margin-right: auto;
padding : 8px;
border : 1px dashed magenta;
max-width : 500px;
}
#container:after {
content : "";
clear: both;
display: block;
}
.article:first-child {
margin-left : -4px;
}
.article:last-child {
margin-right : -4px;
}
.article {
float: left;
width : 33.333%;
margin-right : 4px;
border : 1px solid blue;
}
<div id="container">
<div class="article">
A content
</div>
<div class="article">
B content
</div>
<div class="article">
C cotntent
</div>
</div>
<br />
<hr />
<button id="rotateBtn">Stop rotate</button>
Hope it helps :)
There are so many ways to do this. Here is a simple JSFiddle using jQuery that leaves you lots of room for improving. While you can certainly use a variable to hold the DIV's content I just used a hidden DIV as a temporary content holder. You could also optimize the rotateNews() function by holding the four DIV pointers in variables e.g. var $news1 = $("#new1"); placed first in the function.
Pure javascript solution: store the contents of you divs inside variables, then reassign the content of each div to other divs according to your needs.
setInterval(function(){
var contents_n1 = document.getElementById("news1").innerHTML;
var contents_n2 = document.getElementById("news2").innerHTML;
var contents_n3 = document.getElementById("news3").innerHTML;
document.getElementById("news1").innerHTML = contents_n3;
document.getElementById("news2").innerHTML = contents_n1;
document.getElementById("news3").innerHTML = contents_n2;
}, 30000);

hide one div when another is showing in jQuery?

I am trying to hide a div when another one is visible.
I have div 1 and div 2.
If div 2 is showing then div 1 should hide and if div 2 is not showing then div 1 should be visible/unhide.
The function would need to be function/document ready upon page load.
I've tried this but I'm not having any luck, can someone please show me how I can do this.
<script>
window.onLoad(function () {
if ($('.div2').is(":visible")) {
$(".div1").fadeOut(fast);
} else if ($('.div2').is(":hidden")) {
$('.div1').fadeIn(fast);
}
});
</script>
Add a class of hidden to each div, then toggle between that class using jQuery. By the way, window.onload is not a function, it expects a string like window.onload = function() {}. Also, put fast in quotations. I don't know if that's required, but that's how jQuery says to do it.
<div class="div1"></div>
<div class="div2 hidden"></div>
.hidden { display: none }
$(document).ready(function() {
if($(".div1").hasClass("hidden")) {
$(".div2").fadeIn("fast");
}
else if($(".div2").hasClass("hidden")) {
$(".div1").fadeIn("fast");
}
});
You should pass a string to the .fadeIn() and .fadeOut() methods.
Instead of .fadeIn(fast) it'll be .fadeIn("fast"). Same for .fadeOut().
And in general since you're already using jQuery it's better to wrap your code like this:
$(function () {
// Code goes here
});
It looks like you're using jquery selectors (a javascript library). If you're going to use jquery make sure the library is loaded properly by including it in the document header (google makes this easy by hosting it for you <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>)
With jQuery loaded you can do it like this
$(document).ready(function(){
if ($('.div1').is(":visible")) {
$('div2').hide();
}
else if ($('.div2').is(":visible")) {
$('div1').hide();
}
});
WORKING EXAMPLE: http://jsfiddle.net/HVDHC/ - just change display:none from div 2 to div 1 and click 'run' to see it alternate.
You can use setTimeout or setInterval to track if these divs exists
$(function() {
var interval = window.setInterval(function() {
if($('#div2').hasClass('showing')) {
$('#div1').fadeOut('fast');
}
if($('#div2').hasClass('hidden')) {
$('#div1').fadeIn('fast');
}
}, 100);
// when some time u don't want to track it
// window.clearInterval(interval)
})
for better performance
var div1 = $('#div1')
, div2 = $('#div2')
var interval ....
// same as pre code

Simple Ticker (jQuery)

<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
I'd like to show only one li at a time using slide effect, thats it. I'd like to avoid using plugins for something as simple as this.
Thanks in advance for your help.
i have made something simple up for you (based on your description), just to point you in the right direction:
check it out here:
http://jsfiddle.net/meo/ACenH/234/
function slider(container, delay){
$container = $(container) // select the container elements and store them in a variable
if ( !$container.length ){ return fasle; } // checks if the slider exists in your dom. if not the function ends here...
var slides = $container.length, // gives back the total LI's you have
slide = 0 // set the actual li to show
setInterval(function(){ // set a Interval for your main function
if (slide == slides - 1) { // if the actual slide is equal the total slides (-1 because eq is 0 based and length gives back the number of elements in the jQuery object) the slide counter is set to 0
$container.slideDown(); // and all slides a shown again
slide = 0;
} else {
$container.eq(slide).slideUp(); //slides the selected slide up i think you could think of a solution with .next() instead of eq()
slide++; // slide counter +1
}
}, delay)
}
slider('ul > li', 2000); // call your slider function
Your question already mentions jquery as the javascript framework of choice. The best place you can start is the jquery docs on hiding:
http://api.jquery.com/hide/
and sliding:
http://api.jquery.com/slideUp/
http://api.jquery.com/slideDown/
http://api.jquery.com/slideToggle/

Categories

Resources