Push older text while fading in new text - javascript

I would like new text, as it is fading in, to push the older text down instead of having new text appear after old text. Is this possible? Have been having a lot of difficulty figuring this out.
Here is the javascript:
var $el= $('.fader').map(function() {
return this;
}).get();
$el.forEach(function (eachdiv){
var text = $(eachdiv).text(),
words = text.split(".");
var html = "";
for (var i = 0; i < words.length; i++) {
html += "<span>" + words[i] + " </span>" + '<br/>';
$(eachdiv).html(html).children().hide().each(function(i){
return $(this).delay(i*200).fadeIn(200);
});
}
});
The solution does seem to involve the use of prepend, but I'm not sure where to place prepend within the code.

Try For loop like this instead of yours. Just Giving you an idea. give fadeIn effect as per your data arrives.
for (var i = 0; i < words.length; i++) {
html.prepend("<span>" + words[i] + " </span>" + '<br/>');
$(eachdiv).html(html).children().hide().each(function(i){
return $(this).fadeIn(200);
});
}

This seemed to work in the return line:
return $(this).delay(i*200).prependTo(eachdiv).fadeIn(200);
Thanks for introducing me to prepend, Sindhoor!

Related

InnerHTML doesn't work - Advanced function

I'm beginner in JS. But, after many hours, i'm really close to the wanted result.
I declare my JS Function in head part
function getPrice(price) {
var tabPrice = price.split("");
var html = "";
var virguleIndex = null;
for (var index = 0; index < tabPrice.length; ++index) {
var priceNumber = tabPrice[index];
if (priceNumber == ',') {
virguleIndex = index;
html += "<span class='p-c'>" + priceNumber + "</span>";
} else if (priceNumber == '-') {
html += "<span class='p-d'>" + priceNumber + "</span>";
} else if (index > virguleIndex && virguleIndex != null) {
html += "<span class='p-" + priceNumber + " p-small'>" + priceNumber + "</span>";
} else {
html += "<span class='p-" + priceNumber + "'>" + priceNumber + "</span>";
}
}
var div = document.getElementsByClassName('price');
div[0].innerHTML = html;
}
and my div in body part
<div class="price"></div>
I made some test - And my function getPrice works perflectly
https://image.noelshack.com/fichiers/2018/02/4/1515663887-functionwork.jpg
Some, the only fail (I think) is that the innerHTML don't work and don't write de var html content in div class price.
I haven't idea yet after many (many) hours of looking.
Can you help me ?
Thanks in advance,
Ludovic
By going through your image it is clear your DOM is not ready. So Please call your function inside this Block.
(function() {
// your page initialization code here
// the DOM will be available here
//Call Your function inside this block. it will work ex. getPrice("100");
})();
Some news (I worked on this few hours), I check for the dom charging. I tried (thank for you answer) the call function / transpose the code and the end / forcing the function after the dom loading (with document.addEventListener("DOMContentLoaded", function(event) {)
Console log still working. But my div still empty :/
Thanks again !

Bad html formatting with jQuery.html()

I have something that I can't understand and i'm struggling with that for 2 days.
For the story, I'm using VICOPO api to get zipcode/city (France only I think).
The thing is that the code I'm generating is not really good interpreted by jQuery (or maybe I'm doing it wrong)
Here is the code:
$('#postcode').val($('#postcode').val().toUpperCase());
if ($('#postcode').val().length == 5)
{
var $ville = $('#postcode');
$.vicopo($ville.val(), function (input, cities) {
if(input == $ville.val() && cities[0]) {
if (cities.length == 1)
$('#city').val(cities[0].city);
else
{
var html = '';
html += '<div style=\'text-align:center\'>';
for (var i=0; i<cities.length; i++)
{
var v = cities[i].city;
// --- HERE IS MY PROBLEM ---
html += '<p onclick=\'alert(\'' + v + '\');\'>' + v + '</p>';
}
html += '</div>';
console.log(html);
$('#multi_ville').html(html);
}
}
});
When I inspect the elements in the multi_div this is what I get:
<p onclick="alert(" billey');'>BILLEY</p>
<p onclick="alert(" flagey-les-auxonne');'>FLAGEY-LES-AUXONNE</p>
etc ....
And when I inspect the console log, all looks correct:
<p onclick='alert('BILLEY');'>BILLEY</p>
<p onclick='alert('FLAGEY-LES-AUXONNE');'>FLAGEY-LES-AUXONNE</p>
<p onclick='alert('VILLERS-LES-POTS');'>VILLERS-LES-POTS</p>
etc ....
If someone have an idea or what I'm doing wrong, it would cool.
(may I mention, this code is in a smarty tpl file surrounded with the {literal} tag)
Try to create self closed tags via jquery and then append them to #multi_ville, here is an example:
// create div element
var div = $('<div/>', {
'style' : 'text-align:center'
});
for (var i=0; i<cities.length; i++)
{
var v = cities[i].city;
// create p element with click event and then append it to div
$('<p/>').on('click', function() {
alert(v);
}).text(v).appendTo(div);
}
$('#multi_ville').append(div);
EDIT It seems that my code above always alert the last city when we click on a element, that's because alert takes the value that v variable has at the time it runs, to solve this we can use let statement:
let v = cities[i].city;
Or a function:
for (var i=0; i<cities.length; i++) {
var v = cities[i];
createPTag(v, div);
}
function createPTag(v, div) {
$('<p/>').on('click', function() {
alert(v);
}).text(v).appendTo(div);
}
Instead of
html += '<p onclick=\'alert(\'' + v + '\');\'>' + v + '</p>';
try this:
html += '<p onclick="alert(\'' + v + '\');">' + v + '</p>';
Here's some info on when and how to use double/single quotes.
EDIT:
Also, check the else on this if statement:
if (cities.length == 1)
You need a closing curly bracket (}) to close in the else. It should be added directly after this line:
$('#multi_ville').html(html);

Issue when trying to use jQuery's window.open function in combination with a for-loop to iterate through an array

Let's say I have an array of links like this:
var playlist = [
"",
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
And a bunch of boxes generated in the following way:
for(var i = 1; i < 5; i++) {
$(".container").append("<div class='luke luke-" + i + "'>" + "<h3 class='nummer'>Luke " + i + "</h3> " + "</div>");
}
I then want to iterate through this array to open a specific link when a box is clicked.
for(var i = 1; i < 5; i++) {
$(".luke-" + i).click(function(){
window.open(playlist[i], "_blank");
})
}
That doesn't seem to work at all, however the example below does exactly what I want.
$(".luke-1").click(function(){
window.open(playlist[1], "_blank");
})
$(".luke-2").click(function(){
window.open(playlist[2], "_blank");
})
$(".luke-3").click(function(){
window.open(playlist[3], "_blank");
})
$(".luke-4").click(function(){
window.open(playlist[4], "_blank");
})
$(".luke-5").click(function(){
window.open(playlist[5], "_blank");
})
So this works, but it's a pain in the ass to setup as I want to have 25 boxes in total and this solution offers little to no flexibility if I want to increase or decrease that amount at a later time. What am I doing wrong with the for-loop that's causing issues here?
If I use
console.log(playlist[i]);
inside of the for-loop, it simply returns "undefined" regardless of what box I click in case that helps.
You can do this much easier and simpler using a data attribute.
HTML
<div class="container"></div>
Javascript/jQuery
var playlist = [
"",
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
for(var i = 1; i < 5; i++) {
$(".container").append("<div class='luke' data-url='" + playlist[i] + "'>" + "<h3 class='nummer'>Luke " + i + "</h3> " + "</div>");
}
$('.luke').click(function() {
window.open($(this).data('url'));
});
Demo Here
You are not doing right.
EXAMPLE FIDDLE
var playlist = [
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
var container = $("#container");
for(var i = 1; i < 5; i++) {
container.append('<div class="luke" db-id="'+ i + '"><h3 class="nummer">Luke ' + i + '</h3></div>');
}
$(".luke").click(function(i){
window.open(playlist[$(this).attr('db-id')], "_blank");
});
for(var i = 1; i < 5; i++) {
$(".luke-" + i).click(function(i){
window.open(playlist[i], "_blank");
})
}
The click event will launch your function only inside the scope of the loop. This means that once the loop have finished, ( and counting from 0 to 5 is insanely fast for your computer ) there's no more function attached to your click event. In other terms, as long as i < 5, your click function will work as you expect, but after that, the click event will no longer call the function you created.
One solution could to be attach a function to the onclick attribute in the HTML like this :
for(var i = 1; i < 5; i++) {
$('<div/>', {
'class': 'luke luke-' + i,
'click': yourFunction(i)
}).appendTo(${'.container'});
$('<h3/>', {
'class':'nummer',
'html': 'Luke' + i
}).appendTo(${'.luke-'+i})
}
and then write a function like this :
function yourFunction(index){
window.open(playlist[index], "_blank");
}
Simple way by using Hyperlink
hyperlinks
Demo Here

Get element by tag and class

I have a script
var firstImg = row.getElementsByTagName('img')[0];
and later
if (x){ firstImg.src='/images/checked.png'; }
I'd like to define that the img should be of class='something'
(Get first img with class='something')
Use the
querySelectorAll('img.classname')[0]
this returns first image with class set to class name. However jQuery is better!!
$('img.classname')
Just set it...
firstImg.className += "something";
...or...
firstImg.classList.add("something");
If you can get away with not supporting older browsers.
Further Reading (disclaimer: link to my own blog).
If you're intending to get elements with a certain class name, you can use...
document.getElementsByClassName("something");
...or...
document.querySelectorAll(".something");
Keep in mind getElementsByClassName() isn't in <= IE8.
You can use...
var getElementsByClassName(nodeList, className) {
var i, results = [];
for (i = 0; i < nodeList.length; i++) {
if ((" " + nodeList[i].className + " ").indexOf(" " + className + " ") > -1) {
results.push(nodeList[i]);
}
}
return results;
}
Of course, it's super simple if you're using jQuery...
$(".something");
this selects the first img with class='something':
var firstImg = $('img.something')[0];
If you could not throw away the old browsers, then you need a loop.
var imgs = row.getElementsByTagName('img'),
some_class = 'something',
i, first_img;
for (i = 0; i < imgs.length; i++) {
if ((' ' + imgs[i].className + ' ').indexOf(' ' + some_class + ' ') > -1) {
first_img = imgs[i];
break;
}
}

How to replace strings from an array

I'm working on a piece of code that uses regex expressions to do a find/replace for emoticons in a chat. However, I want to use the same array of values and output them as a reference.
The regex works fine for my searches, but when I tried to do a replace on the regex search string before I output it for my help, I still end up with a slash.
:\)
:\(
var emotes = [];
emotes[0] = new Array(':\\\)', 'happy.png');
emotes[1] = new Array(':\\\(', 'sad.png');
function listEmotes(){
var emotestext = '';
for(var i = 0; i < emotes.length; i++){
//Tried this and it doesn't seem to work
//var emote = emotes[i][0];
//emote.replace('\\', '');
emotestext += '<ul>' + emote + ' <img src="emotes/' + emotes[i][1] + '"></ul>';
}
return emotestext;
}
Your problem is that str.replace doesn't change the original variable but instead returns a new one. Try this out:
var emotes = [
[':\\\)', 'happy.png'],
[':\\\(', 'sad.png']
];
function listEmotes(){
var emotestext = '';
for(var i = 0; i < emotes.length; i++){
var emote = emotes[i][0].replace('\\', ''); // See what I did here?
emotestext += '<ul>' + emote + ' <img src="emotes/' + emotes[i][1] + '"></ul>';
}
return emotestext;
}

Categories