Append HTML but have separate fadeIn on document click - javascript

I am appending a div every time the user clicks anywhere on the page. I want the div's to fadeIn but the way I first did this each div that was appended had the same ID. This is a problem if I want each letter div to fadeIn separately. So I tried to use a count to make each div I append have a separate name but this hasn't work. Each time a new div is appended all appended divs fadeIn not just the one just recently added. How might I change this?
var count = 0;
if(firstLetter != "") {
count++;
//Create a new circle letter by inserting new div class
$("p").append('<div class="circle' + count +'" style="border-radius: 50%;width: 36px;height:36px;padding:8px;background:#FF7D5C;color:black;text-align:center;font:32px Arial, sans-serif;display:inline-block;margin-right:4px;margin-bottom:4px;">' + firstLetter.toUpperCase() + '</div>').hide().fadeIn('slow');
}
Many Thanks :)

Try this. In your code all the divs play the effect because the element returned by all the functions that you're calling is the < p > element.
$("p").append('<div class="circle' + count +'" style="border-radius: 50%;width: 36px;height:36px;padding:8px;background:#FF7D5C;color:black;text-align:center;font:32px Arial, sans-serif;display:inline-block;margin-right:4px;margin-bottom:4px;">' + firstLetter.toUpperCase() + '</div>');
$("p").children().last().hide().fadeIn();
OR a simpler way
$("p div:last").hide().fadeIn();

Related

How to show/hide certain number of divs using a single button?

I have elements that should show or hide after the first five elements. When I click on 'Load More...' with an id #loadMore, it will trigger to show all the elements and change the div id to #showLess to execute a different set of action. So, when I click #showLess to hide the rest of the thumbnails, nothing happens. The $('#showLess').click(function() isn't executing but instead executes the $('#loadMore').click(function() again.
Here's a jsfiddle.
jQuery:
var vidThumbnail = "";
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
for (i = 0; i < 25; i++) // loop thru 25 thumbnails
{
vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
$('.section.thumbnail .thumb').append(vidThumbnail);
if(i > 5) // when it reaches the first five thumbnails, hide the rest
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
}
$('#loadMore').click(function() // show them all
{
$('.section.thumbnail .thumb .video-thumbnail').show();
$(this).attr('id', 'showLess'); // change id to show less
$(this).text('Show Less...'); // change text value
});
$('#showLess').click(function()
{
// slice the first five, hide the rest
$(elements).slice(5).each(function(i)
{
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
});
$(this).attr('id', 'loadMore'); // change id to show less
$(this).text('Load More...'); // change text value
});
I've fixed a bit your code because you do some mistakes.
Look here: https://jsfiddle.net/sbz51wdz/36/
I explain your error:
When you define a click action, jQuery add an event on a matched DOM elements. If you simply change the id attribute and attach another event of that new ID before the action of changing ID was started, jQuery will not find anything with the new ID. My favourite solution is add the click event on single element with a fixed class or id. Inside the function, everytime, check if the element has or not a class, and then do the right action. Just use somenthing like $(this).hasClass(...)
After this, is better to define single function called when it needs.
Last but not least, it's important to attach assignments after the context is defined in the DOM. so var elements = $('.section.thumbnail .thumb > .video-thumbnail'); this have to be written after the foreach cycle that generate the elements.
Hope its help! :)
You are changing the id of the div on click so should use $(document) and bind all ids with that like
$(document).on('click', '#loadMore', function()
https://jsfiddle.net/sbz51wdz/35/
I have created a div class name "test" and put the loadMore div inside it for binding. You need it cause a hidden or invisible div need to bind in every event occurrence in jquery. then i modified the jquery code in this below way and it works.
var vidThumbnail = "";
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
for (i = 0; i < 25; i++) // loop thru 25 thumbnails
{
vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
$('.section.thumbnail .thumb').append(vidThumbnail);
if(i > 5) // when it reaches the first five thumbnails, hide the rest
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
}
$('.test').on('click', '#loadMore', function() // show them all
{
$('.section.thumbnail .thumb .video-thumbnail').show();
$(this).attr('id', 'showLess'); // change id to show less
$(this).text('Show Less...'); // change text value
});
$('.test').on('click', '#showLess', function()
{
// slice the first five, hide the rest
var j = 6;
$('.section.thumbnail .thumb .video-thumbnail').each(function(i)
{
$('.section.thumbnail .thumb .video-thumbnail').eq(j).hide();
j++;
});
$(this).attr('id', 'loadMore'); // change id to show less
$(this).text('Load More...'); // change text value
});

jQuery append div in a div to the bottom of a scroll window

I am trying all the stuff I read here and all over the net, but it looks like I am not getting it somehow.
I have been fiddling it for a while but still it does not work.
<div id="blokscubes" class='main'>
<div id="alldivs">
</div>
<div id="report" class="mydivs"></div>
$('#report').text('One');
for (i=1;i < 11;i++){
var newid = 'report-' + i.toString();
var oldid = '#report-' + (i-1).toString();
$('#alldivs').append('<div id=' + newid + ' class="mydivs">'+ newid + '</div>');
var hashold = '#' + newid;
$(hashold).animate({"scrollTop": $(hashold)[0].scrollHeight}, 300);
$(oldid).css('position','relative');
}
The last added div always hangs to the bottom of the screen,but not to the bottom of the scrolled down screen.
What am I missing or not writing correctly?
Thanks
The issue is the last div has position:absolute instead of relative.
You can set the CSS to have the mydivs have a relative position, or you can set the last div created to have position:relative (You missed the last one out)
DEMO
I'm not sure why you first set position:absolute for .mydiv and then via js you change to position: relative. Problem is that your last div has still absolute position. You can fix this like this:
$('#report-1').text('One');
$('#report-1').css('position','relative');
for (i=2;i < 10;i++){
var newid = 'report-' + i.toString();
var oldid = '#report-' + (i-1).toString();
$('#blokscubes').append('<div id=' + newid + ' class="mydivs">'+ newid + '</div>');
var hashold = '#' + newid;
$(hashold).animate({"scrollTop": $(hashold)[0].scrollHeight}, "fast");
$('#' + newid).css('position','relative');
}
I would use position:fixed on the last Element, relative to a parent that you should surround $('#blokscubes') with, and create a height on a new empty second to last Element, so there is no word over word overlap. Note that position:fixed and position:absolute are relative to the closest parent that is position:relative or the document.documentElement (html tag), which is position:static. So, you basically have your positioning wrong. Also, there is usually no need to create non-dynamic Elements with jQuery. Just use HTML and CSS.

Javascript to fade text in, one word at a time, works with one div, but not multiple divs?

I'm trying to fade in one word at a time from a div. The below code works fine for one div but when I have multiple divs, it does not do it sequentially.
Here is the fiddle : http://jsfiddle.net/zlud/6czap/110/
Can anyone see an obvious problem? Any suggestions to print one line after the other would be greatly appreciated. (So the text in the second div will be printed after the first div is done.)
<html>
<div class="example">These are some words that </br> should be faded in one after the other.</div>
<div class="example"> No way some words that </br> should be faded in one after the other.</div>
</html>
JavaScript
var $el = $('.example').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>";
$(eachdiv).html(html).children().hide().each(function(i){
return $(this).delay(i*500).fadeIn(700);``
});
}
});
How about this?
I am assuming you dont need a delay in animation, instead you need them to appear one after the other.
var words, $el;
var arrEl = [];
// loop through each div and populate the array with the container (div) element and its text content split
$('.example').each(function(){
var $this = $(this);
arrEl.push({el:$this,words : $.trim($this.text()).split(" ")});
$this.empty();
});
//This will the startup function
function fadeIn(){
var len = arrEl.length, obj = arrEl.shift() || {}; //get the top item from array and remove it from the array using array.shift
$el = obj.el; //get the container from the item
words = obj.words; //get the array of words
//if there are any items in the array start the animation process for this item.
if(len) window.setTimeout(transitionElement, 0);
}
function transitionElement(){
var wlen = words.length,
span = $('<span/>', {'class':'hide'}).append(" " + words.shift()); //remove and get the top text string from the word array wrap it in span with a class "hide" which will hide it by default
window.setTimeout(function(){
if(wlen) //if words are available anymore then call show word
showWord(span);
else //else call fadeIn to process the next container in the arrEl array of items
fadeIn();
},0);
}
function showWord(span){
span.appendTo($el).fadeIn(500, transitionElement); // append the span to the container with an animation duration of 500ms and in the complete callback of this invoke transitionElement to process the next word or next item. Here there is no delay required since this will invoked only when the transition of first word is completed
}
//Start animation process
fadeIn();
Fiddle
fadeIn() callback syntax
Array.shift
Jquerys animation functions have a callback in the parameter list. This callback will be executed after the animation completes. Or maybe it's that i is passed by reference.
You should pick on div at a time to work on and continue to the next one ones the first is done. Now you attach the delay and fade-in to each word in each div at the same time. Initiate the animation of the second div by a trigger when the first one is done or something like that?

Remove any element if it's count is bigger than x amount

I've looked around a bit and I cannot seem to find out how to remove a DOM element if its count gets over 50 amount. Basically it's similar to a chat.
JS
function append(aVal) {
document.getElementById('elem').innerHTML += "<br/>" + aVal;
}
Usage
appendvalues("<span>Your message " + message + ".</span>");
HTML
<div id="elem" class="container"></div>
I'm trying to remove the br & span tags. I feel that making a class for the span tag would be better since I have other span tags on the page.
I assume you want to do it FIFO...
function append(aVal) {
var el = document.getElementById('elem');
el.insertAdjacentHTML("beforeend", "<br/>" + aVal);
var spans = el.getElementsByTagName("span");
if (spans.length > 50) {
el.removeChild(spans[0].nextSibling);
el.removeChild(spans[0]);
}
}
Note that I'm using .insertAdjacentHTML instead of .innerHTML +=.... This is a much less destructive way to add content from HTML.
Does this do what you want?
$("#elem > span:gt(50)").remove();

using replaceWith on all child inputs JQuery

Basically on .show() I've been trying to have all of the inputs convert to image tags with the img src equaling the original inputs value like this:
var currentPage = $('.three_paj_els:visible');
var nextPage = currentPage.next('.three_paj_els');
var the_parent_div_id = currentPage.attr('id');
nextPage.show(function() {
$('div#' + the_parent_div_id + ':input').each(function() {
var the_image_SRC = $(this).val();
$(this).replaceWith('<img src="' + the_image_SRC + '" ')
})
})
Been at it for a few hours now. I want only the ones in that specific div that gets shown to convert.
here's a fiddle of what I've been working on http://jsfiddle.net/Utr6v/100/
when you click the next button, the <input type="hidden" /> tags should convert to <img> tags and the images should show.
Thanks a bunch in advance.
-Sal
currentPage doesn't seem to have an ID. But you're overcomplicating it - if you have the element, you can use that to execute jQuery functions on. You don't need to do an element -> ID -> element conversion since that's pointless.
To find descendants you need to put a space between the element selector and the descendant selector, otherwise the selector applies to the elements themselves. In your case, you can just use .find.
Also, you were missing the closing tag of the image.
http://jsfiddle.net/Utr6v/101/
// I guess you want to replace with images on the new page, not the one
// which gets hidden
nextPage.find(':input').each(function() {
var the_image_SRC = $(this).val();
$(this).replaceWith('<img src="' + the_image_SRC + '">')
});

Categories