Fading in appended elements one at a time - javascript

I have an array with IDs and I am loading elements with these IDs from another page.
$.each(idArr, function() {
var divline = '<div class="line" id="' + this + '">';
var url = 'allitems.php #' + this + ' div';
$('#the-list').append($(divline).load(url).hide().fadeIn());
});
It works fine but I would like the loaded elements to fade in one at a time, or at least not all att once. I cannot figure out how to use .delay with my code. Or is there maybe another way?
Thank you :)

$.each(idArr, function(i,el) {
var divline = $('<div />', {'class':'line', id: el}),
url = 'allitems.php #' + el + ' div';
$('#the-list').append(divline.load(url).hide().delay(i*1000).fadeIn());
});

A simple solution is to use setTimeout :
$.each(idArr, function(i) {
var divline = '<div class="line" id="' + this + '">';
var url = 'allitems.php #' + this + ' div';
setTimeout(function(){
$('#the-list').append($(divline).load(url).hide().fadeIn());
}, i*1000);
});

Try this way:
$(".elements").each(function(i, e) { $(e).delay(i * 400).fadeIn(400); });

Related

HTML tag in JavaScript

I am returning a HTML tag in JavaScript which has values
var code = 'brand':
return `<div class="${code}_label">${code.toUpperCase()}</div>`;
I don't want to use $ and I want to concatenate through + in JavaScript
var code = 'brand':
return `<div class=code+"_label">code.toUpperCase()</div>`;
But this is not giving the expected output.
Can anyone please help?
Thanks in advance
Your quoting is a bit wrong:
function createTag() {
var code = 'brand';
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';
}
console.log(createTag());
Another solution using dom api would be:
function createTag() {
var code = 'brand';
var div = document.createElement("div");
div.id = code + '_label';
div.innerText = code.toUpperCase();
return div;
}
console.log(createTag());
Without ES6 you can use single quotes:
var code = 'brand':
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';
I think it's the problem with how you use quotes.
var code = 'brand':
return `<div class=` + code + `_label">` + code.toUpperCase() + `</div>`;
You are using wrong quoting.
var code = 'brand';
return '<div class="' + code + '_label">' + code.toUpperCase() + '</div>';

jQuery append adding elements recursively

I'm trying to make from scratch a jQuery Form builder but I'm having some problems.
When you add a new field to the form generator, it works, but when you try to add a new field, it appends the new field plus one. If you try again, then it adds 3 elements, etc. The code is inside a function, then it is called when the document is ready.
I spent so many hours and I haven't a clear vision of where's the problem (sorry)
function addField() {
var formAddField = $("#form-add-field");
var formConstructorForm = $("#form-constructor-form");
var addFieldButton = $("#add-field-button");
var fieldLabelName = $("#field-label-name");
var formGenerated = $("#form-generated");
var formGeneratedForm = formGenerated.find("form");
var fieldIdForm = $("#field-id-form");
var fieldTypeSelect = $("#field-type-select");
var inputTypeForm = $("#input-type-form");
var inputTypeSelect = $("#input-type-select");
var field = '';
var label = '';
var inputGroup = '';
formAddField.on("click", function (e) {
e.preventDefault();
addFieldButton.addClass("disabled");
formConstructorForm.addClass("show");
fieldTypeSelect.on("change", function () {
var fieldTypeSelected = fieldTypeSelect.val();
switch (fieldTypeSelected) {
case 'input':
inputTypeForm.show();
addFieldButton.removeClass("disabled");
field = '<input class="validate" id="' + fieldIdForm.val() + '" type="' + inputTypeSelect.val() + '">';
break;
case 'select':
inputTypeForm.hide();
addFieldButton.removeClass("disabled");
field = '<select id="' + fieldIdForm.val() + '"></select>';
break;
case 'textarea':
inputTypeForm.hide();
addFieldButton.removeClass("disabled");
field = '<textarea class="materialize-textarea" id="' + fieldIdForm.val() + '"></textarea>';
break;
}
});
addFieldButton.on("click", function (e) {
e.preventDefault();
label = '<label for="">' + fieldLabelName.val() + '</label>';
inputGroup = '<div class="input-field col s12">' + '\n' + field + '\n' + label + '\n' + '</div>';
formConstructorForm[0].reset();
formConstructorForm.removeClass("show");
$(inputGroup).appendTo(formGeneratedForm);
});
});
}
Here's the complete jsfiddle with the functions and when have they been called.
Could anyone give me a hand on this? Thanks!
The problem in your code is that you are adding an extra click event every time you press the button. In the updated fiddle below it will remove the previous listeners before adding the new one.
It may not be the perfect solution but will solve your problem.
addFieldButton.off('click');
addFieldButton.on("click", function(e) {
e.preventDefault();
label = '<label for="">' + fieldLabelName.val() + '</label>';
inputGroup = '<div class="input-field col s12">' + '\n' + field + '\n' + label + '\n' + '</div>';
formConstructorForm[0].reset();
formConstructorForm.removeClass("show");
$(inputGroup).appendTo(formGeneratedForm);
});
https://jsfiddle.net/5d7poco0/
you are binding events every time you press addfield button change your
addFieldButton.on( "click", function(e) {
to the following
addFieldButton.unbind('click').on( "click", function(e) {
EDIT
A better way would be using on and off rather than using bind unbind method if youre using a version greater than jQuery v1.7

JSON div style background image link doesn't have slashes?

I am creating a list of thumbnails with JSON and I have problem with this line of code:
videoHTML += '<div class="user-background" style="background-image: url("' + video.channel.video_banner + '");">';
I can see div element and everything in it except background-image link doesn't have slashes.
This is the code that I see in debugger elements:
<div class="user-background" style="background-image: url(" https:="" static-cdn.jtvnw.net="" jtv_user_pictures="" esl_csgo-channel_offline_image-c9f885982daa1c83-1920x1080.png");"=""><div class="user-background" style="background-image: url(" https:="" static-cdn.jtvnw.net="" jtv_user_pictures="" esl_csgo-channel_offline_image-c9f885982daa1c83-1920x1080.png");"=""><img class="user-logo" src="https://static-cdn.jtvnw.net/jtv_user_pictures/esl_csgo-profile_image-546a0c1883798a41-300x300.jpeg" alt="user image"><p class="user-name">ESL_CSGO</p></div><img class="video-image" src="http://static-cdn.jtvnw.net/previews-ttv/live_user_esl_csgo-320x180.jpg"><h1 class="game-name">Counter-Strike: Global Offensive</h1><br><i></i><span class="views-number">41304</span><p class="short-date-format date0">2012-06-11T13:36:21Z</p></div>
Can You help me by explaining what I am doing wrong with quotation marks?
(I believe that they are causing this problem.)
Here is the code for you to understand it better:
$(document).ready(function(){
$.getJSON( "https://api.twitch.tv/kraken/streams", function( data ) {
var items = [];
var videoHTML ='<ul>';
//Get data and create video grid
$.each(data.streams, function(i, video){
if(i < 9) { //get only first 9 data
var videoDate = $.format.date(video.channel.created_at, "MMM dd yyyy");
videoHTML += '<li class="video-stream ' + video.channel.language + '">';
videoHTML += '<div class="user-background" style="background-image: url("' + video.channel.video_banner + '");">';
videoHTML += '<img class="user-logo" src="' + video.channel.logo + '" alt="user image">';
videoHTML += '<p class="user-name">' + video.channel.display_name + '</p>';
videoHTML += '</div>';
videoHTML += '<a href="#" onclick="popup(\'' + video.channel.name + '\')">';
videoHTML += '<img class="video-image" src="' + video.preview.medium + '"></a>';
videoHTML += '<h1 class="game-name">' + video.game + '</h1><br/>';
videoHTML += '<i></i>';
videoHTML += '<span class="views-number">' + video.viewers + '</span>';
videoHTML += '<p class="short-date-format date' + i + '">' + videoDate + '</p>';
videoHTML += '</li>';
// var userId = "'#userBackground" + i +"'";
alert(userId);
// console.log(video._id);
// console.log(data.streams[i].game);
// console.log(data.streams[i]._links.self);
// console.log(data.streams[i].preview.medium);
} else {
return false;
}
});
videoHTML += '</ul>';
videoHTML += '<div class="clearfix"></div>';
$('#placeholder').html(videoHTML);
}); //getJson
}); //end ready
UPDATE I found your problem. You have to change the " around the style to \'. Like so:
videoHTML += '<div class="user-background" style=\'background-image: url("' + $.trim(video.channel.video_banner) + '");\'>';
See it working with your corrected code here.
I rewrote the whole thing and showed you a few fundamental features of jQuery. Keep in mind, it's not necessarily better, per say, but perhaps more effecient and easier to follow. Within JS alone, there's a dozen different ways to write this. Within jQuery, a million. I could easily have made this a lot shorter, and if for myself, I would do it MUCH different. However, I hope this shows you some of the different uses of jQuery, as well as understanding on why variable control can be so important. I actually didn't see charlietfl's code working. The background still doesn't show up. However, as you'll see in my example, not only did I narrow down to the "problem", I also made it work, but not with anything fancy. I just used basic jQuery!
Keep in mind, jQuery has a well written, easy to follow API. Everything I use here is easily find-able there!
CodeSnippet
function buildList(data) {
if (data) {
var videoHTML = $('<ul />'),
clearFix = $('<div />', { 'class': '' }),
items = [];
$.each(data.streams, function(i, video){
if(i < 9) {
var videoDate = video.channel.created_at, // $.format.date(video.channel.created_at, "MMM dd yyyy"),
li = $('<li />', { 'class': 'video-stream' }).addClass(video.channel.language).appendTo(videoHTML),
div = $('<div />', { 'class': 'user-background' }).appendTo(li),
imgLogo = $('<img />', { alt: 'user image', 'class': 'user-logo' }).attr('src', video.channel.logo).appendTo(div),
pUser = $('<p />', { 'class': 'user-name', html: video.channel.display_name }).appendTo(div),
a = $('<a />', { href: 'javascript:void 0' }).data('vidName', video.channel.name).appendTo(li),
imgPrev = $('<img />', { 'class': 'video-image' }).attr('src', video.preview.medium).appendTo(a),
h1 = $('<h1 />', { 'class': 'game-name' }).appendTo(li),
br = $('<br />').appendTo(li),
ita = $('<i />').appendTo(li),
span = $('<span />', { 'class': 'views-number' }).html(video.viewers).appendTo(li),
pDate = $('<p />', { 'class': 'short-date-format' }).addClass('date' + i).appendTo(li);
// And now we can zero in on your issue with ez, by moveing that one thing here
try {
console.log(video.channel.video_banner);
div.css('backgroundImage', 'url("' + video.channel.video_banner + '")');
}
catch(err) { console.log(err); }
}
else return false;
});
$('#placeholder').append(videoHTML, clearFix);
}
}
$(function() { // jQuery shorthand for $(document).ready(function(){
$.getJSON("https://api.twitch.tv/kraken/streams", buildList);
// the following uses our STATIC element to assign click event to our DYNAMICALLY added anchors
$('#placeholder').on('click', '.video-stream a', function(e) { popup($(this).data('vidName')); });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="placeholder"></div>
jsFiddle for playing!

Manipulating JQuery .text() output

I am building a Twitter like site that is fed random tweets that I want to export to the website in a particular manner. I have most of my requirements met up to this point, the only issue I am having is turning the jQuery text of a Twitter user and handle it into a link that can be clicked.
My code snippet below exhibits my work so far:
<script>
$(document).ready(function(){
var $body = $('.middle');
$body.html();
var index = streams.home.length - 1;
var newTweets = function(index){
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class=tweetBox></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message + tweet.created_at);
$tweet.appendTo($body);
index -= 1;
}
}
newTweets(index);
$('button').on('click', function(){
index = streams.home.length - 1;
newTweets(index);
});
});
</script>
The line that is giving the issue is $tweet.text('#' + tweet.user + ': ' + tweet.message + tweet.created_at);
I want to take tweet.user and convert it into a click-able link. Any suggestions on ways to attack this would be very much appreciated.
You have to use the HTML function of jQuery. http://api.jquery.com/html/
like this:
var link = $('<a>', {text: tweet.user, href: '#'}).prop('outerHTML');
$tweet.html('#' + link + ': ' + tweet.message + tweet.created_at);
it will do the work.
If I understand correctly, then this is what you want
var link = $('<a>', {text: tweet.user, href: '#'}).prop('outerHTML');
$tweet.html('#' + link + ': ' + tweet.message + tweet.created_at);

Elements added with appendTo() not immediately available

I'm having a problem with elements added with appendTo() not being immediately available in the DOM.
First, I'm reading some data from a JSON file and then appending some html to a div. Then I'm calling a random shuffler plugin to show one of the added divs at a time.
jsonUrl = "js/performers.json";
$.getJSON(jsonUrl, function(json) {
$.each(json.performers, function(i, performer) {
var html = '<div class="performer_mini">';
html += '<img src="' + performer.thumbnail + '" alt="' + performer.name + '" /><br />';
html += performer.name + '<br /></div>';
$(html).appendTo("div#performer_spotlight");
});
});
$("#performer_spotlight").randomShuffler(".performer_mini", 3000, 3000, 9000);
The random shuffler does the following:
(function($) {
$.fn.randomShuffler = function(shuffledElements, fadeInTime, fadeOutTime, timeout) {
fadeInTime = fadeInTime || 3000;
fadeOutTime = fadeOutTime || 3000;
timeout = timeout || 9000;
$(shuffledElements).hide();
var $old_element;
var $new_element;
var old_index = 0;
var new_index = 0;
function shuffleElement() {
$old_element = $new_element;
old_index = new_index;
while ($(shuffledElements).length > 0 && old_index == new_index) { // don't display the same element twice in a row
new_index = Math.floor(Math.random()*$(shuffledElements).length);
}
$new_element = $(shuffledElements + ":eq(" + new_index + ")");
if ($old_element != undefined) {
$old_element.fadeOut(fadeOutTime, function() {
$new_element.fadeIn(fadeInTime);
});
} else {
$new_element.fadeIn(fadeInTime);
}
setTimeout(shuffleElement, timeout);
}
$(this).show();
shuffleElement();
}
})(jQuery);
The first time the shuffleElement() function is called $(shuffledElements).length equals 0, so no element is displayed. On the next call to shuffleElement(), the elements added with appendTo() are available and one is selected at random as expected. Everything works correctly after that.
Is there some way to refresh the DOM or make these elements available to jQuery immediately after I add them with appendTo()? Any other suggestions for how to accomplish this?
When exactly do you call randomShuffler? You call this function after the AJAX-request succeeds? I have always believed that the element added by appendTo available immediately after the addition.
This code works very well for me:
<script language="javascript">
var test = "<div class=\"test\">1</div>";
$(test).appendTo("div#performer_spotlight");
$("div.test").html("<b>Hello</b>");
</script>
Yes, like #MeF Convi says you need to call the plugin only after the getJSON finishes:
$.getJSON(jsonUrl, function(json) {
$.each(json.performers, function(i, performer) {
var html = '<div class="performer_mini">';
html += '<img src="' + performer.thumbnail + '" alt="' + performer.name + '" /><br />';
html += performer.name + '<br /></div>';
$(html).appendTo("div#performer_spotlight");
});
$("#performer_spotlight").randomShuffler(".performer_mini", 3000, 3000, 9000);
});

Categories

Resources