Slide new entry ajax - javascript

Hello i need to display by slide multiple entry by ajax my script work just for one entry
var newTxt = ['hello', 'hi'];
for(var i = 0; i <= newTxt.length; i++) {
$('#txt').prepend('<li class="none">' + newTxt[i] + '</li>');
$('#txt li:first-child').toggleClass("none", 2000);
}
i use css and toggleClass for animation
li { width:100px; }
li.none { width:0px; }
The animation work with 1 entry but with more not work
u have solution for display by slide one by one ?
Thanks you
Edit (now its work but all setTimeout exucute in same time)
var newTxt = ['hello', 'hi'];
for(var i = 0; i <= newTxt.length; i++) {
setTimeout(function(y) {
$('#txt').prepend('<li style="width:0">' + newTxt[i] + '</li>');
$('#txt li:first-child').animate({'width':'100px'}, 1000);
} (i), (i * 2000));
}
Demo https://jsfiddle.net/HHsxc/292/ i need to slide first wait slide seconde wait ...

Related

WAI’s carousel example slider has different behavior with < > arrows vs. 123 links at the bottom

https://www.w3.org/WAI/tutorials/carousels/working-example/
Has anyone noticed that the slide transitions are a bit abrupt?
For example:
When we're doing it on with left < > right arrow, slide out the old one, slide in the new one.
But when we're doing it with 1 2 3 links at the bottom, right now it just goes to white and slides in the new one.
I just hope you feel this should have a similar experience, as many people would follow W3C as a standard? Please provide at least the fix so that we all could have it right a way.
Also I have reported same concern in the official W3C GitHub as well:
https://github.com/w3c/wai-tutorials/issues/571
You need to change some JS, HTML and CSS.
JS Change.....
First replace whole function body of setSlides function. You can check the difference by comparing this code with the old one.
function setSlides(new_current, setFocusHere, transition, announceItemHere) {
// Focus, transition and announce Item are optional parameters.
// focus denotes if the focus should be set after the
// carousel advanced to slide number new_current.
// transition denotes if the transition is going into the
// next or previous direction.
// If announceItem is set to true, the live region’s text is changed (and announced)
// Here defaults are set:
setFocus = typeof setFocusHere !== 'undefined' ? setFocusHere : false;
transition = typeof transition !== 'undefined' ? transition : 'none';
announceItem = typeof announceItemHere !== 'undefined' ? announceItemHere : false;
new_current = parseFloat(new_current);
var length = slides.length;
var new_next = new_current+1;
var new_prev = new_current-1;
// If the next slide number is equal to the length,
// the next slide should be the first one of the slides.
// If the previous slide number is less than 0.
// the previous slide is the last of the slides.
if(new_next === length) {
new_next = 0;
} else if(new_prev < 0) {
new_prev = length-1;
}
// Reset slide classes
//for (var i = slides.length - 1; i >= 0; i--) {
//slides[i].className = "slide";
//}
var prevLeft = 0;
for (var i = new_current - 1; i < -1; i--) {
prevLeft += 100;
slides[i].style.left = '-' + prevLeft + '%';
}
slides[new_current].style.left = 0;
var nextLeft = 0;
for (var i = new_current + 1; i < length; i++) {
prevLeft += 100;
slides[i].style.left = '-' + nextLeft + '%';
}
// Add classes to the previous, next and current slide
//slides[new_next].className = 'next slide' + ((transition == 'next') ? ' in-transition' : '');
slides[new_next].setAttribute('aria-hidden', 'true');
//slides[new_prev].className = 'prev slide' + ((transition == 'prev') ? ' in-transition' : '');
slides[new_prev].setAttribute('aria-hidden', 'true');
//slides[new_current].className = 'current slide';
slides[new_current].removeAttribute('aria-hidden');
// Update the text in the live region which is then announced by screen readers.
if (announceItem) {
carousel.querySelector('.liveregion').textContent = 'Item ' + (new_current + 1) + ' of ' + slides.length;
}
// Update the buttons in the slider navigation to match the currently displayed item
if(settings.slidenav) {
var buttons = carousel.querySelectorAll('.slidenav button[data-slide]');
for (var j = buttons.length - 1; j >= 0; j--) {
buttons[j].className = '';
buttons[j].innerHTML = '<span class="visuallyhidden">News</span> ' + (j+1);
}
buttons[new_current].className = "current";
buttons[new_current].innerHTML = '<span class="visuallyhidden">News</span> ' + (new_current+1) + ' <span class="visuallyhidden">(Current Item)</span>';
}
// Set the global index to the new current value
index = new_current;
}
And replace the whole body of function slidenav.addEventListener('click', function(event) { by below code.
slidenav.addEventListener('click', function(event) {
var button = event.target;
if (button.localName == 'button') {
if (button.getAttribute('data-slide')) {
//stopAnimation();
//setSlides(button.getAttribute('data-slide'), true);
var nextOrPrev;
var getCurrent = document.querySelector('button.current');
var diff = getCurrent.getAttribute('data-slide') - button.getAttribute('data-slide');
diff = (diff < 0) ? (-1 * diff) : diff;
if (getCurrent.getAttribute('data-slide') < button.getAttribute('data-slide')) {
nextOrPrev = 'prev';
} else {
nextOrPrev = 'next';
}
setSlides(button.getAttribute('data-slide'), false, nextOrPrev, announceItem);
} else if (button.getAttribute('data-action') == "stop") {
stopAnimation();
} else if (button.getAttribute('data-action') == "start") {
startAnimation();
}
}
}, true);
And HTML change.
Remove all prev next and current class from li
And set inline css
left: 0; for first li
left: 100%; for second li
left: 200%; for third li
left: 300% for fourth li
..................
..................
add more 100% for each next li
Remove all visibility: hidden
Please let me if it works for you.

JQuery Letters fade in randomly

This is my first time coding in JQuery. Below is my code:
var div = document.getElementById('fadeletters1'),
letters = div.textContent.split('');
while(div.hasChildNodes()) div.removeChild(div.firstChild);
for(var i = 0; i < letters.length; i++) {
var letter = document.createElement('span'),
style = 'opacity ' + (Math.random() * 5 + 1) + 's linear';
letter.appendChild(document.createTextNode(letters[i]));
letter.style.WebKitTransition = letter.style.transition = style;
letter.style.opacity = 0;
div.appendChild(letter);
}
setTimeout(function() {
for(var i = 0; i < div.childNodes.length; i++) {
div.childNodes[i].style.opacity = 1;
}
}, 0);
<div id=fadeletters1>Helllooo This is a test for the website</div>
So the letters do fade in but then in the starting of the animation, letter are kinda visible and then fades in after couple seconds. I want it to pop up from 0 visibility to 100 visibility as its fades in.
I am trying to acheive something like this site does: http://method.digital/
You're changing the rate at which the transition takes place, instead you want to change the delay before the transition starting:
var div = document.getElementById('fadeletters1'),
letters = div.textContent.split('');
while(div.hasChildNodes()) div.removeChild(div.firstChild);
for(var i = 0; i < letters.length; i++) {
var letter = document.createElement('span'),
style = 'opacity 0.6s linear',
delay = (Math.random() * 4) + 's';
letter.appendChild(document.createTextNode(letters[i]));
letter.style.WebKitTransition = letter.style.transition = style;
letter.style.WebKitTransitionDelay = letter.style.transitionDelay = delay;
letter.style.opacity = 0;
div.appendChild(letter);
}
setTimeout(function() {
for(var i = 0; i < div.childNodes.length; i++) {
div.childNodes[i].style.opacity = 1;
}
}, 0);
<div id=fadeletters1>Helllooo This is a test for the website</div>
If you want to run it for multiple divs you can wait until the first is complete before moving onto the next (this example only appears to work sometimes, make sure to hit refresh before running):
function RunAnimation(target,delay) {
var div = document.getElementById(target),
letters = div.textContent.split('');
while (div.hasChildNodes()) div.removeChild(div.firstChild);
setTimeout(function(){
for (var i = 0; i < letters.length; i++) {
var letter = document.createElement('span'),
style = 'opacity 0.6s linear',
delay = (Math.random() * 4) + 's';
letter.appendChild(document.createTextNode(letters[i]));
letter.style.WebKitTransition = letter.style.transition = style;
letter.style.WebKitTransitionDelay = letter.style.transitionDelay = delay;
letter.style.opacity = 0;
div.appendChild(letter);
}
setTimeout(function() {
for (var i = 0; i < div.childNodes.length; i++) {
div.childNodes[i].style.opacity = 1;
}
}, 0);
}, delay);
}
RunAnimation('fadeletters1')
RunAnimation('fadeletters2', 5000);
RunAnimation('fadeletters3', 10000);
<div id="fadeletters1">Helllooo This is a test for the website</div>
<div id="fadeletters2">This is a second div which also fades in</div>
<div id="fadeletters3">And who knows maybe you want a third</div>
The thing is there is two delays...
One for the animation and one for a timeout. This is the timeout that really gives the effect you are looking for.
// Get the letters from the original string.
var letters = $("#fadeletters1").text().split("");
// Remove the original string.
$("#fadeletters1").text("");
// Create a span for each letters and append them to the document.
letters.forEach(function(item,index){
var span = $("<span class='fade'>").text(item);
$("#fadeletters1").append(span);
});
// Animate each spans
$(document).find(".fade").each(function(){
// Random delay
var delay = Math.random();
var letter = $(this);
// Set a timeout to animate the spans
setTimeout(function(){
letter.animate({"opacity":1},delay*1000);
},delay*3000);
});
.fade{
opacity:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fadeletters1">Helllooo This is a test for the website</div>

setTimeout within a for loop not executing the function passed to it

i'm trying to make a "console typing effect" with js, and in the next function i take the text of an element, then i use a "for" loop for slicing that text and paste in within with a delay.
After debugging the code in chrome i can see that javascript doesn't run the setTimeout... it just ignores it.
function type() {
var text = document.querySelector('.console-effect').textContent;
for (var i = 0; i <= text.length; i++) {
setTimeout(function() {
document.querySelector('.console-effect').textContent = text.substr(0, i)
}, 50);
}
}
type();
Your setTimeouts are all executing at the same time, because the for loop does not wait for them to execute on each iteration. You have to delay each timeout using a value such as 50*i.
Then, to preserve the value of i in this case, you'll need to use a closure. Otherwise, by the time your timeouts come to an end, the loop will be over, and i will be the final value, for all of them.
var text = document.querySelector('.console-effect').textContent;
for (var i = 0; i <= text.length; i++) {
(function(i) {
setTimeout(function() {
document.querySelector('.console-effect').textContent = text.substr(0, i);
}, 50*i);
})(i);
}
body{background: #333;}
.console-effect{color: #0f0; font-family: monospace; font-size: 2em;}
<div class="console-effect">This is some example text</div>
Is not a good idea to make functions inside a loop in Javascript, I had bad experiences with it.
This code done this way should work correctly:
function type() {
var text = document.querySelector('.console-effect').textContent;
var loopFunc = function(i) {
return function() {
document.querySelector('.console-effect').textContent = text.substr(0, i)
};
};
for (var i = 0; i <= text.length; i++) {
setTimeout(loopFunc(i), 50);
}
}
type();
I didn't want to believe #blex, but he was correct about the scope. He was right on both points he made, but the closure stunned me. How have I never encountered this and been forced to puzzle my way out before?
So the idea here is that instead of scheduling a dozen or so calls to your function at the beginning, you only schedule the next call. After that one is called, it sees if it needs to schedule the next.
function type() {
var text = document.querySelector('.console-effect').textContent;
var i = 0;
var typeNext = function() {
++i;
document.querySelector('.console-effect').textContent = text.substr(0, i);
if(i < text.length) {
setTimeout(typeNext, 50);
}
}
setTimeout(typeNext, 50);
}
type();
<span class="console-effect">This is a test</span>
var text = document.querySelector('.console-effect').textContent;
var index = 0;
setInterval(function(){
document.querySelector('.console-effect').textContent = text.substr(0, index);
if(index == text.lenght){
clearInterval(this);
}
index++;
},1000);
Do something like this.
function type() {
var text = document.querySelector('.console-effect').textContent;
document.querySelector('.console-effect').textContent = '';//clear content
for (var i = 0; i <= text.length; i++) {
setTimeout(function(j) {
document.querySelector('.console-effect').textContent += text[j];// or .charAt(j)
}, 50 * i, i);
// 50 * i sets timeout for each iteration
// i (3rd arg) passes to the inner function
}
}
type();
Better version.
function type(text) {
var textObj = document.querySelector('.console-effect');
for (var i = 0; i <= text.length; i++) {
setTimeout(function(ch) {
textObj.textContent += ch;
}, 50 * i, text[i]);
// 50 * i sets timeout for each iteration
// i (3rd arg) passes to the inner function
}
}
type('.console-effect');
a solution without 50*i, take a look at the css effect too. You problem is setTimeout is executed asynchronously (the 'control flow' doesn't wait for those 50ms), so they are fired all together with value i = text.length (if your text is small enough)
<p class="console-effect">console effects</p>
<script>
function type() {
var i=0;
var t = document.querySelector('.console-effect').textContent;
var fn = setInterval(function() {
print_text(++i,t,fn)
}, 500);
}
function print_text(i,t,fn){
if(i <= t.length){
document.querySelector('.console-effect').textContent = t.substr(0, i)
} else clearInterval(fn)
}
type();
</script>
<style>
#-webkit-keyframes blinker {
from { opacity: 1.0; }
to { opacity: 0.0; }
}
.console-effect:after{
content:'_';
text-decoration: blink;
-webkit-animation-name: blinker;
-webkit-animation-duration: 0.2s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function:ease-in-out;
-webkit-animation-direction: alternate;
}
</style>
setTimeout run only once(in your case after delay of 50ms).
For this purpose you should use setInterval

fading a paragraph in word by word using jquery?

<p class="example">i want to split this paragraph into
words and fade them in one by one</p>
the jquery/js:
$(document).ready(function() {
var $txt = $(".example")
,$words = $txt.text()
,$splitWords = $words.split(" ");
$txt.hide();
for(i = 0; i < $splitWords.length; i++){
// i want fade in each $splitWords[i]
//$splitWords[i].fadeIn(.... - i tried this doesnt work
}
});
im trying to split the paragraph into words, and fade them in one by one, thier might be an easier way to do this without splitting the words, please shed some light on this. thanks
Text by itself can't have an opacity, therefore you must wrap the text with an element that can have opacity (such as a span). You can then fade in those spans.
Try this:
http://jsfiddle.net/6czap/
var $el = $(".example:first"), text = $el.text(),
words = text.split(" "), html = "";
for (var i = 0; i < words.length; i++) {
html += "<span>" + words[i] + " </span>";
}
$el.html(html).children().hide().each(function(i){
$(this).delay(i*500).fadeIn(700);
});
Update for benekastah: http://jsfiddle.net/6czap/3/
var $el = $(".example:first"), text = $.trim($el.text()),
words = text.split(" "), html = "";
for (var i = 0; i < words.length; i++) {
html += "<span>" + words[i] + ((i+1) === words.length ? "" : " ") + "</span>";
};
$el.html(html).children().hide().each(function(i){
$(this).delay(i*200).fadeIn(700);
});
$el.find("span").promise().done(function(){
$el.text(function(i, text){
return $.trim(text);
});
});
You will need to fade in elements, text nodes can't have a opacity.
See demo at jsfiddle.net
var p = $("p.example").hide(); // possible flash! You should add some script
// to the <head> that writes a stylesheet
// to hide them right from the start
(function oneParagraph(i) {
if (p.length <= i)
return;
var cur = p.eq(i),
words = cur.text().split(/\s/),
span = $("<span>"),
before = document.createTextNode("");
cur.empty().show().append(before, span);
(function oneWord(j) {
if (j < words.length) {
span.hide().text(words[j]).fadeIn(200, function() {
span.empty();
before.data += words[j]+" ";
oneWord(j+1);
});
} else {
span.remove();
before.data = words.join(" ");
setTimeout(function(){
oneParagraph(i+1);
}, 500);
}
})(0);
})(0);
If you need only one paragraph, you can leave out all the things beloning to the oneParagraph function - just make cur the selected element.
If you want to have a smoother animation, you'd need to animate multiple words at the same time (demo), or dont fade but append letterwise like in here. Alternatively you could make the fading-time dependent on the length of the current word.
You'll have a couple problems with the suggestions mentioned so far.
First, splitting and then hiding the text in Javascript will result in a Flash of Unstyled Content. Second, the number of reflows is going to be pretty bad for long text.
Rather than hiding the text, consider setting the foreground and background to the same color, and then changing it back.

Without using jquery, how to cycle through images to make a simple slideshow

You have a div, with 3 images in it.
How to create a simple slideshow that cycles through the images, and displays each image for 5 seconds and goes back to the first image when done and continues looping.
Without using jquery or any other framework.
(function () {
var imgs = document.getElementById('your_div').getElementsByTagName('img'),
index = 0;
imgs[0].style.display = 'block';
setInterval(function () {
imgs[index].style.display = 'none';
index = (index + 1) % imgs.length;
imgs[index].style.display = 'block';
}, 5000);
}());
Example HTML: http://jsfiddle.net/Zq7KB/1/
Edit: Saw a more elegant example above that used .length.
You can use setInterval to set up the timed callback, and set the src of an img element:
window.onload = function() {
var slides = [ "path_to_image_one",
"path_to_image_two",
"path_to_image_three" // ...
],
index = 0,
timer = 0;
// Show the first slide
showNextSlide();
// Show "next" slide every five seconds
timer = setInterval(showNextSlide, 5000);
// The function we call to show the "next" slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
...where your markup for the image is:
<img id="theImage" src="path_to_initial_placeholder">
Note that I've stored the timer handle in timer but not used it. This is just because you might use it to cancel the timer if you need to stop the slideshow.
Update: Just saw that you want to get the images from a div somewhere (whereas above I've supplied the paths in the code itself). Simple enough to create slides dynamically; revised edition of the above that grabs the images that are direct children of the div with the ID "theDiv":
window.onload = function() {
var slides = [],
index = 0,
timer = 0,
node;
// Get the slides
for (node = document.getElementById('theDiv').childNodes;
node;
node = node.nextSibling) {
if (node.nodeType == 1 && node.tagName == "IMG") {
slides.push(node.src);
}
}
// Show the first slide
showNextSlide();
// Show "next" slide every five seconds
timer = setInterval(showNextSlide, 5000);
// The function we call to show the "next" slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
Well you'd have to get a handle for the <div> first, so if it has an "id" value:
var theDiv = document.getElementById("imgContainer");
Now you just have to set up a timer to cycle through the images:
(function(div, sleep) {
var idx = 0;
var imgs = div.getElementsByTagName('img');
function showOne() {
for (var i = 0; i < imgs.length; ++i)
imgs[i].style.display = 'none';
imgs[idx].style.display = '';
idx = (idx + 1) % imgs.length;
setTimeout(showOne, sleep);
}
showOne();
})(theDiv, 5000);
var image = new Array('/img/1.jpg', '/img/2.jpg', '/img/3.jpg');
setTimeout("show_next()",5000);
function show_next()
{
var container = document.getElementById('image_container');
container.innerHTML = "<img src='" + image[i] + "' />";
if(i==2) { i = 1; }else { i = i + 1; }
}
I thought this was a nice simple answer, but there were a couple of errors.
setInterval rather than setTimeout and the initial index was not set. I also amended to load first image immediately.
var image = new Array('imgs/18/P1050294-XL.jpg', 'imgs/18/P1050293-XL.jpg', 'imgs/18/P1040984-XL.jpg', 'imgs/18/P1040983-XL.jpg', 'imgs/18/P1040982-XL.jpg');
var path = 'mypath';
document.getElementById('slideShow').innerHTML = "<img width='600px' src='" + path + image[0] + "' />" // Load First image
var i = 1; // Set counter to second image, for first use of loop
setInterval("show_next(path)",5000);
function show_next(path)
{
var container = document.getElementById('slideShow');
container.innerHTML = "<img width='600px' src='" + path + image[i] + "' />";
if(i==4) { i = 0; } else { i = i + 1; }
}

Categories