Using fadein and append - javascript

I am loading JSON data to my page and using appendTo() but I am trying to fade in my results, any ideas?
$("#posts").fadeIn();
$(content).appendTo("#posts");
I saw that there is a difference between append and appendTo, on the documents.
I tried this as well:
$("#posts").append(content).fadeIn();
I got it, the above did the trick!
But I get "undefined" as one of my JSON values.

If you hide the content before you append it and chain the fadeIn method to that, you should get the effect that you're looking for.
// Create the DOM elements
$(content)
// Sets the style of the elements to "display:none"
.hide()
// Appends the hidden elements to the "posts" element
.appendTo('#posts')
// Fades the new content into view
.fadeIn();

I don't know if I fully understand the issue you're having, but something like this should work:
HTML:
<div id="posts">
<span id="post1">Something here</span>
</div>
Javascript:
var counter=0;
$.get("http://www.something/dir",
function(data){
$('#posts').append('<span style="display:none" id="post' + counter + ">" + data + "</span>" ) ;
$('#post' + counter).fadeIn();
counter += 1;
});
Basically you're wrapping each piece of the content (each "post") in a span, setting that span's display to none so it doesn't show up, and then fading it in.

This should solve your problem I think.
$('#content').prepend('<p>Hello!</p>');
$('#content').children(':first').fadeOut().fadeIn();
If you are doing append instead then you have to use the :last selector instead.

You have to be aware that the code doesn't execute linearly. The animated stuff can't be expected to halt code execution to do the animation and then return.
commmand();
animation();
command();
This is because the animation uses set timeout and other similar magic to do its job and settimeout is non-blocking.
This is why we have callback methods on animations to run when the animation is done ( to avoid changing something which doesn't exist yet )
command();
animation( ... function(){
command();
});

$(output_string.html).fadeIn().appendTo("#list");

assuming you have the following in the css defined:
.new {display:none}
and the javascript should be :
$('#content').append('<p class='new'>Hello!</p>');
$('#content').children('.new').fadeIn();
$('#content').children.removeClass('new');
$('#content').children('.new').hide();

First is convert received data to jQuery Object.
Second, hide it immediately.
Third, append it to a target node.
And, after this all, we can clearly use necessary animation, just like fadeIn :)
jNode = $("<div>first</div><div>second</div>");
jNode.hide();
$('#content').append(jNode);
jNode.fadeIn();

im have a exprensive,for this:
$("dt").append(tvlst.ddhtml);
$("dd:last").fadeIn(700);

I tried what you said did the trick but is not working.
it worked with the following code
$("div").append("content-to-add").hide().fadeIn();

Related

show all the values with .html [duplicate]

Lets say I have an empty div:
<div id='myDiv'></div>
Is this:
$('#myDiv').html("<div id='mySecondDiv'></div>");
The same as:
var mySecondDiv=$("<div id='mySecondDiv'></div>");
$('#myDiv').append(mySecondDiv);
Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:
A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection.
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div').
EDIT: To see the sheer quantity of checks that jQuery performs, have a look here, here and here.
innerHTML is generally the faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as element.innerHTML = ... -- as I mentioned, there are a bunch of checks and optimisations occurring.
The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:
jQuery(Array(101).join('<div></div>'));
There are also issues of readability and maintenance to take into account.
This:
$('<div id="' + someID + '" class="foobar">' + content + '</div>');
... is a lot harder to maintain than this:
$('<div/>', {
id: someID,
className: 'foobar',
html: content
});
They are not the same. The first one replaces the HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appends it to the first.
One jQuery Wrapper (per example):
$("#myDiv").html('<div id="mySecondDiv"></div>');
$("#myDiv").append('<div id="mySecondDiv"></div>');
Two jQuery Wrappers (per example):
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);
You have a few different use cases going on. If you want to replace the content, .html is a great call since its the equivalent of innerHTML = "...". However, if you just want to append content, the extra $() wrapper set is unneeded.
Only use two wrappers if you need to manipulate the added div later on. Even in that case, you still might only need to use one:
var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();
if by .add you mean .append, then the result is the same if #myDiv is empty.
is the performance the same? dont know.
.html(x) ends up doing the same thing as .empty().append(x)
Well, .html() uses .innerHTML which is faster than DOM creation.
.html() will replace everything.
.append() will just append at the end.
You can get the second method to achieve the same effect by:
var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);
Luca mentioned that html() just inserts hte HTML which results in faster performance.
In some occassions though, you would opt for the second option, consider:
// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");
// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);
Other than the given answers, in the case that you have something like this:
<div id="test">
<input type="file" name="file0" onchange="changed()">
</div>
<script type="text/javascript">
var isAllowed = true;
function changed()
{
if (isAllowed)
{
var tmpHTML = $('#test').html();
tmpHTML += "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').html(tmpHTML);
isAllowed = false;
}
}
</script>
meaning that you want to automatically add one more file upload if any files were uploaded, the mentioned code will not work, because after the file is uploaded, the first file-upload element will be recreated and therefore the uploaded file will be wiped from it. You should use .append() instead:
function changed()
{
if (isAllowed)
{
var tmpHTML = "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').append(tmpHTML);
isAllowed = false;
}
}
This has happened to me . Jquery version : 3.3.
If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html will end up adding only the last object to the parent element, whereas .append will add all the list objects as children of the parent element.

jquery body on hover cannot target other DIVS

I am trying to access my own javascript function from within a:
$("body").on("mouseenter",".noteNode",function(){});
The trouble seems to be that when I am inside the function above jQuery will not allow me to get access to other elements?
Let me elaborate further:
Actual code I want to use I've jsfiddled: http://jsfiddle.net/uJ2Yb/8/
I believe the function is being called as I had wanted it to be, but as you can see $(this) is not able to target the actual div which is being hovered, and so when trying to pass this data to the other function it just doesn't arrive - why is this? I believe it's a scope problem but I have tried a few ways to solve it and searched S.O without much luck yet.
The reason I need to use $("body").on is because I am creating the DIV's (which will be hovered) on the fly with JS.
As you can see the hover function is working fine and firing as it should do, but totally unable to access anything in the DOM which I don't understand
.
[Edit] so to clarify: http://jsfiddle.net/uJ2Yb/8/
I am trying to pass the ID of the DIV (which was created BY JS) over to my own function in which i want to try and access the DIVs offset parameter - but i am unable to do so, you will see in my revised fiddle that i am just getting 'undefined' in my alert box which is not what i wanted - i am still convinced that this is because of a scope issue.
try this updated fiddle: http://jsfiddle.net/uJ2Yb/7/
function myFunction(someVar){ alert(someVar); }
$("body").on("mouseenter",".noteNode",function(event){
myFunction(event.target.innerHTML );
//alert( event.target.innerHTML );
});
Please Assign Unique Id To Your Divs
try This Code
function myFunction(someVar){ alert(someVar); }
$(document).ready(function(){
$("body").append('<div class="noteNode" id="a">Note Node</div>');
$("body").append('<div class="noteNode" id="b">Note Node</div>');
$("body").append('<div class="noteNode" id="c">Note Node</div>');
});
$("body").on("mouseenter",".noteNode",function(){
myFunction( $(this).attr("id") );
alert( $(this).attr("id") );
});

fadeIn() / fadeOut() animation not playing

Below I have this piece of code which I use to filter products with using a drop-down menu. The content of the #child_cat division changes based on the value attribute of the anchor tag:
$('#brandsort').change(function(){
$('#child_cat a').fadeOut(500);
$('[value="' + $(this).val() + '"]').fadeIn();
if ($('#brandsort option:selected').text() === "") {
$('#child_cat a').fadeIn(500);
}
});
The code will filter out the products that do not match their option value, but it won't play the animation. Right now, it acts more like a delayed .show() / .hide() function than anything. Please enlighten me from any wrongdoing in my code or what I could possibly be doing wrong aside from that.
EDIT:
I know the people on SO would normally like some hands-on help from one of you, but in this case I was specifically only asking for "enlightenment". Just some verbal input of what I could have been doing wrong.
To fulfill your request of providing some HTML, you'll find it here: http://jsfiddle.net/HJPN8/3/
There was a few mistakes in the logic that made this not work. Firstly, the reason you couldn't see the fade animate happen is because fade uses the css property opacity. Opacity only works on block and inline-block elements, and you were using the .fadeOut() on a tags which are display:inline. So that can be fixed easily with this:
#child_cat a{
display:block;
}
Next you're using .fadeOut() and .fadeIn() which both run at the same time meaning that the animations would both collide and not work properly. So you need to use callback functions to correctly time them. Below is the code I have refactored, I've included a lot of comments so you can see how it all works. The fade functions have been replaced with .animate() which is a lower end function that gives you more control which we need in this situation.
One last thing is that you were using the value attribute on your products, this isn't recommended as this property is specific to the options tag. If you wish to create custom attributes then the standard way is to prepend them with "data-" which you can see I've done here: http://jsfiddle.net/HJPN8/6/
$(function(){
var brandsort = $('#brandsort');
var products = $('#child_cat a');
brandsort.on('change', function(e){
var val = brandsort.val();
// If search is blank then select all products to show else filter specific products.
var filteredProducts = (val == '') ? products : products.filter('[data-value="' + val + '"]');
// Hide products and set callback for when the animation has finished.
// If we don't use a callback, the products will animate out and in at the same time, ruining the effect.
products.animate({opacity: 0}, 300).promise().done(function(){
// Now that he products' opacity is 0, we set them to display block to remove them from the flow of the DOM.
products.css({display: 'none'});
// Now Bring the filtered products back and animate them in again.
filteredProducts.css({display: 'block'}).animate({opacity: 1}, 500);
});
});
});

How to use jquery with variable assigned

How can I use a variable in jQuery. as you see in script snippet, I assign a variable "divname" with value, and when i use 'Jquery" to fade out. it is not working. What I really need is, when image is hover, the description will be show up as fading in, when mouse is gone, the the description should be gone. thanks in advance.
Script snippet
$j('.img_nofade').hover(function(){
$j(this).animate({opacity: .5}, 300);
var i = $j(this).attr('titlename');
var divname = "'#titleID" + i + "'";
//alert (divname);
$j(divname).fadeIn();
},
function(){
$j(this).animate({opacity: 1}, 300);
$j(divname).fadeOut();
}
);
HTML code
<img class="img_nofade' src="image-1.gif" titleid='1" />
<div id="titleID1">my image title 1 </div>
<img class="img_nofade' src="image-2.gif" titleid='2" />
<div id="titleID2">my image title 2 </div>
<img class="img_nofade' src="image-3.gif" titleid='3" />
<div id="titleID3">my image title 3 </div>
No need to use the ' char, just:
var divname = "#titleID" + i;
And in the hover's handlerOut function, the divname is already out of scope, you should define it again.
There are a few issues I see.
Your attributes in your HTML are mixing single and double quotes. You need to use one or the other.
$j(this).attr('titlename'); - The attribute name doesn't match your HTML attributes. (titlename vs titleid)
You have a scoping issue with the var divname. You define it in your mouseover event which means it won't be defined in your mouseleave event. You should just use the next method to get a reference to your div. $j(this).next().fadeIn() This would prevent the need for trying to find the titleID in the first place.
There are a few issues here.
1) You have some typos in the HTML. Be careful about single and double quotes. Not all browsers will automatically correct those kinds of errors, and if Javascript can't find the HTML it's looking for, then your code will break.
2) jQuery provides some excellent resources for getting elements without having to fall back on the varname-style thing (i.e. var titleId = $(this).attr('titleId')+i;)
Instead, you can do something like this:
<img class="img_nofade" src="image-1.gif"/>
<div class="description">my image title 1 </div>
<img class="img_nofade" src="image-2.gif"/>
<div class="description">my image title 2 </div>
<img class="img_nofade" src="image-3.gif"/>
<div class="description">my image title 3 </div>
I got rid of the titleId attribute and changed the divs from id="TitleID1" to "description". It's more generic, but it's also more semantic from a styling standpoint. You won't have to individually style each of those things.
The jQuery would look something like:
$('.img_nofade').hover(function(){
$(this).animate({opacity: .5}, 300);
$(this).next('.description').animate({opacity: 0}, 300);
},function(){
$(this).animate({opacity: 1}, 300);
$(this).next('.description').animate({opacity: 1}, 300);
});
The $.next() method grabs the next element. If you pass in a selector, you can grab the next element with that selector. This is really useful when you're dynamically adding things to the page and want to grab the next one on the list. There are several other ways to do this, this just happens to be the easiest in this scenario, I think.
Finally, you should keep in mind that the .fadeIn() and .fadeOut() methods will change the display attribute to display:none when hiding. This means that in your above example, without any styling, the titles would disappear, causing the images to slide together. That's why I chose to animate on the opacity instead. You can definitely do the fadeIn/fadeOut thing if you have CSS styling those images to keep them from collapsing in on each other.
Good luck.
You have two functions for the hover and have declared divname in the first and then you are trying to use it in the second. This won't work because it is not in scope of the second function.
Instead of using the divname in this case you could use $j(this).next() to select the next sibling, in this case the div following the img and call fadeIn() and fadeOut() that way.
$j('.img_nofade').hover(function(){
$(this).next().fadeIn();
}, function(){
$(this).next().fadeOut();
});
This isn't too hard
$j('.img_nofade').hover(function(){
var title = 'titleID' + $(this).attr('titleid');
$('#' + title).fadeIn();
}, function(){
var title = 'titleID' + $(this).attr('titleid');
$('#' + title).fadeOut();
});
Try this fiddle
http://jsfiddle.net/cmyks/

Using javascript to insert id into list elements

I am messing around with a deck of cards that I made.I have it set up so that there is a method that spits out cards by suit into a list, so if I want spades I get a <ol> of all of the spades cards. I am now trying to give each <li> element an id depending on what card it is. ace will be <li id="ace"><img src="ace_spades.gif"/></li> king will be <li id="king"><img src="king_spades.gif"/></li> for example.The list is in order from top to bottom akqj1098765432 . I tried doing this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12)
{
$(document).ready(function(){
$("li").eq(counter).attr("id", card_id[counter])
});
counter++;
}
but it doesn't work. I have not really done anything with javascript before besides simple jquery stuff. What am I getting wrong here?
Try this:
$(document).ready(function(){
var card_id = ["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$.each(card_id, function(i,id){
$("li").eq(i).attr('id',id);
});
});
You should try to only have one $(document).ready() function and it's not necessary to use a while() loop.
I think you don't need to call $(document).ready() function in the while. Try this:
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
var counter=0;
while (counter<=12){
$("li").eq(counter).attr("id", card_id[counter]);
counter++;
}
You do not need the document ready function. Place your script just before </body> and after the jquery.js script. This is working for me.
Check working example at http://jsfiddle.net/H8MeG/2/
First of ID's in a webpage have to be unique. Some browsers might ignore id's of elements that have already been used. Other browsers might fail completely...
Second off. you shouldn't use .eq() like that.
You definitely shouldn't add 12 new $(document).ready() statements.
Here's a more reliable version and the example on jsfiddle
var card_id=["ace","king","queen","jack","ten","nine","eight","seven","six","five","four", "three","two"];
$("#spades li").each(function(index){
$(this).attr("class", card_id[index]);
$(this).text(card_id[index]);
});
I also added $(this).text(card_id[index]); so you see it actually works. Try to uses classes for multiple elements that share the same characteristic.
why are you messing with ids at all?
you know that the first item is the ace, the second the king, and so on.
ol.getElementsByTagName('li')[12]='deuce'

Categories

Resources