jQuery: fadeOut() with html(), weird behaviour - javascript

while making a simple random quote machine (part of a coding course I'm attending), I ran into a problem while trying to fade out an element in my HTML, that should then add some new HTML in it and fade it in. Here's the code:
$(".quote-text").fadeOut(function() {
$(this).html("<p>" + quotes[currentQuoteNum] + "</p>").fadeIn();
});
The quotes[currentQuoteNum] just refers to a list of quote strings I have. For some reason, neither the fadeIn or fadeOut functions do not animate correctly. The delay is there before my HTML is updated with a new quote, but the animation is not displayed. Now, if I remove the p element like so:
$(".quote-text").fadeOut(function() {
$(this).html(quotes[currentQuoteNum]).fadeIn();
});
Then it works and both the fadeIn and fadeOut animations are played. I need to have the p element in there, because inside them I'm adding another two elements to create quotation marks around my quote using a special styling class. I omitted those for simplicity. I know there are other ways but I want to know why this is happening.
Obviously this has something to do with adding tags to my HTML, but I have not been able to find out what it is. Please explain?

Code looks fine to me, should not be an issue.
Here is a codepen and it works as it should
Fade codepen
$(".quote-text").fadeOut(function() {
$(this).html("<p>" + "Oh Good"+ "</p>").fadeIn();
});
why not check the content of your variable.Probably its not well formatted

Try this change
$(".quote-text").fadeOut(2000, function() {
$(this).text(quotes[currentQuoteNum]).fadeIn(2000);
});
I just removed the inner <p> tag and replaced html() with text()
Here's working code pen http://codepen.io/anon/pen/wMgWvR

Related

Add html in jquery with differents contents

I have this little script for add differents parts of code to the body in website
WincontentBody=jQuery("<div class='wd_"+idw+"'id='win_container'>OK</div>");
WincontentBody=jQuery("</div>");
jQuery(WincontentBody).fadeIn(3000).appendTo('body');
I try to add code from WincontentBody to body but it doesn't work, some kind of error i have in syntax, because never show div
I think this it's fine but I can't find the problem, the idea it's to add all contents from the variable WincontentBody to the body
Is it possible to do this? Because i can't make it to work
ThankĀ“s in advanced
I went ahead and wrote your question properly for you. Take a look at SO in Spanish.
fadeIn and appendTo are jQuery methods. WincontentBody contains a string. You should first create a new jQuery object with your html.
$(WincontentBody).appendTo('body').fadeIn(3000); //first append, then fade in
If the fadeIn doesn't seem to work, it's probably because you will have to hide the elements (with some css) before inserting them into the page. Otherwise you'll be trying to fade in something that's already visible.
And I don't know if your code is actually formatted like that or it just got wrapped here, but you can't have multiline strings, unless you end each line with \.
Now (after your edit), you are creating two jQuery objects. One with the div and the other with nothing valid.
WincontentBody=jQuery("<div class='wd_"+idw+"'id='win_container'>OK</div>");
//WincontentBody now has the div
WincontentBody=jQuery("</div>");
//WincontentBody now has nothing. The </div> is not being appended to what was in WincontentBody before, you're assigning a new value to it
jQuery(WincontentBody).fadeIn(3000).appendTo('body');
//You're appending WincontentBody (which has nothing valid) to the body
//Also, WincontentBody is already a jQuery instance, no need to call jQuery() again
What you should do is to create your WincontentBody with the html code, as you had before, and then use $(WincontentBody)... or jQuery(WincontentBody).... Or put the whole html code in a single jQuery element like:
var WincontentBody=jQuery("----all the html code at once----");
WincontentBody.appendTo("body").fadeIn(3000);
Try this.
$(document).ready(function() {
WincontentBody = "<div class='wd_asdfas'id='win_container'>OK This is fine.</div>";
$('.displayHere').append(WincontentBody);
$('.displayHere').fadeIn(3000);
});
body { background: #eee }
.displayHere { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
<div class="displayHere">
Hello Buddy
</div>
</body>
Updated
I had made few changes.
I add the div named displayHere. I don't think it is good idea to
give the fade effect to body of the webpage.
In jquery I split the functions to two different functions. Firstly it will update the details and then it will fade in.

How can I fadeIn/fadeOut of text using jQuery (or CSS)?

I'm building a random quote generator and would like to use the fadeIn/fadeOut function when switching between quotes when prompted by a button click. However I'm not sure how to target the text in jQuery, since I am printing the array directly from Javascript like this:
$('.show-quote').text(randomQuote);
Here is the project so far:
http://codepen.io/biancalelei/pen/vLeJVd
I think this is what you want: http://codepen.io/anon/pen/GoMGQL
$('.show-quote').fadeOut(300, function(){
$(this).text(randomQuote).fadeIn(300)
});
First, it will fade out in 300ms. When it is done the attached function will be executed. It changes the text and then fades it back in.
If you don't want the background to fade out as well, you can put the text in extra <div>: http://codepen.io/anon/pen/OMxEvK
You can use $('.show-quote').fadeIn() and $('.show-quote').fadeOut()
You can try this, first fadeOut 300ms and then fadeIn 300ms after that text print
$('.show-quote').fadeOut(300).fadeIn(300).text(randomQuote);
You can chain jQuery functions to achieve the functionality. Something like this:
$('.show-quote').hide().html(randomQuote).fadeIn(1000);
CodePen: http://codepen.io/anon/pen/wMrXyv

Changing page background via Javascript

I have been trying to get this to work for the past 6 hours and I am just unable to do it right. I've looked at the questions and solutions on SO as well to no avail. What am I doing horribly wrong?!?
All I have is a html5 page with no background. In my javascript code I call upon this method when the document is ready:
/*
* Initializes the landing page.
*/
function initializeLanding(){
$('body').css({
'backround':'url("http://40.media.tumblr.com/290e7a272b492735ddf8cd968e657d05/tumblr_nhmg6xYnv41u7ns0go1_1280.jpg")'
});
}
It should be something stupidly simple, and yet here I am. I've tried using single quotes, double quotes, without multiple attributes, etc. I would also much rather not use CSS or DOM properties to change the background, as I have set up way points along the page to change the background upon scrolling past them.
Also, if I call the .css() method and put in new attributes, will it overwrite all the old ones, or just the stated attributes in the latest css() call?
Update: here is where I call the function:
var main = function(){
$(".owl-carousel").owlCarousel();
lorem();
initializeLanding();
}
$(document).ready(main);
you have a spelling mistake.
backround => background.
check this demo
you have a spelling mistake. replace backround to background
function initializeLanding(){
$('body').css({
'background':'url("http://40.media.tumblr.com/290e7a272b492735ddf8cd968e657d05/tumblr_nhmg6xYnv41u7ns0go1_1280.jpg")'
});
}

Basic JQuery .animate() does not work but same CSS can be changed with .css()!

I have a bizzare problem which I have been trying to resolve. Its very basic but I just don't get it. Here it is. I am using JQuery to animate a simple display of a div element to a "block" from "none." I tried the following two options:
$('#fort_link').click(function(){
$('#fort_content').animate({'display':'block'},500);
});
$('#fort_link').click(function(){
$('#fort_content').animate({display:'block'},500);
});
I also tried with the callback function after animation is done and it does alert me but nothing really happens as far as setting the display of the div to block.
But, when I try using simple .css method as shown below, it works, as expected. I am using JQuery 1.10.2. I even tried linking to Google's Jquery UI on the CDN. I am not exactly a novice in these things... May be just missing something stupid? Please help!
$('#fort_link').click(function(){
$('#fort_content').css('display','block');
});
use fadeIn() or fadeOut instead:
$('#fort_link_show').click(function(){
$('#fort_content').fadeIn(500);
});
$('#fort_link_hide').click(function(){
$('#fort_content').fadeOut(500);
});
or fadeToogle() for shorthand.
$('#fort_link').click(function(){
$('#fort_content').fadetoggle(500);
//#fort_content will fadeIn if its hidden, fadeOut if its visible
});
From the jQuery docs:
All animated properties should be animated to a single numeric value,
except as noted below; most properties that are non-numeric cannot be
animated using basic jQuery functionality (For example, width, height,
or left can be animated but background-color cannot be
So basically, you can't 'animate' block.

JQuery: Why is hoverIntent not a function here?

I'm modifying some code from a question asked a few months ago, and I keep getting stymied. The bottom line is, I hover over Anchors, which is meant to fade in corresponding divs and also apply a "highlight" class to the Anchor. I can use base JQuery and get "OK" results, but mouse events are making the user experience less than smooth.
I load JQuery 1.3 via Google APIs.
And it seems to work. I can use the built in hover() or mouseover(), and fadeIn() is intact... no JavaScript errors, etc. So, JQuery itself is clearly "loaded". But I was facing a problem that it seemed everyone was recommending hoverIntent to solve.
After loading JQuery, I load the hoverIntent JavaScript. I've triple-checked the path, and even dummy-proofed the path. I just don't see any reasonable way it can be a question of path.
Once the external javascripts are (allegedly) loaded in, I continue with my page's script:
var $old=null;
$(function () {
$("#rollover a").hoverIntent(doSwitch,doNothing)
});
function doNothing() {};
function doSwitch() {
var $this = $(this);
var $index = $this.attr("id").replace(/switch/, ""); //extract the index number of the ID by subtracting the text "switch" from its name
if($old!=null) $old.removeClass("highlight"); //remove the highlight class from the old (previous) switch before adding that class to the next
$this.addClass("highlight"); //adds the class "highlight" to the current switch div
$("#panels div").hide(); //hide the divs inside panels
$("#panel" + $index).fadeIn(300); //show the panel div "panel + number" -- so if switch2 is used, panel2 will be shown
$old = $this; //declare that the current switch div is now "old". When the function is called again, the old highlight can be removed.
};
I get the error:
Error: $("#rollover a").hoverIntent is not a function
If I change to a known-working function like hover (just change ".hoverIntent" to ".hover") it "works" again. I'm sure this is a basic question but I'm a total hack when it comes to this (as you can see by my code).
Now, for all appearances, it SEEMS like either the path is wrong (I've zillion-checked and even put it on an external site with an HTTP link that I double-checked; it's not wrong), or the .js doesn't declare the function. If it's the latter, I must be missing a few lines of code to make the function available, but I couldn't find anything on the author's site. In his source code he uses a $(document).ready, which I also tried to emulate, but maybe I did that wrong, too.
Again, the weird bit is that .hover works fine, .hoverIntent doesn't. I can't figure out why it's not considered a function.
Trying to avoid missing anything... let's see... there are no other JavaScripts being called. This post contains all the Javascript the page uses... I tried doing it as per the author's var config example (hoverIntent is still not a function).
I get the itching feeling I'm just missing one line to declare the function, but I can't for the life of me figure out what it is, or why it's not already declared in the external .js file. Thanks for any insight!
Greg
Update:
The weirdest thing, since I'm on it... and actually, if this gets solved, I might not need hoverIntent solved:
I add an alert to the "doNothing" function and revert back to plain old .hover, just to see what's going on. For 2 of my 5 Anchors, as soon as I hover, doNothing() gets called and I see the alert. For the other 3, doNothing() correctly does NOT get called until mouseout. As you can see, the same function should apply for any Anchor inside of "rollover" div. I don't know why it's being particular.
But:
If I change fadeIn to another effect like slideDown, doNothing() correctly does NOT get called until mouseout.
when using fadeIn, doNothing() doesn't get called in Opera, but seems to get called in pretty much all other browsers.
Is it possible that fadeIn itself is buggy, or is it just that I need to pass it an appropriate callback? I don't know what that callback would be, if so.
Cheers for your long attention spans...
Greg
Hope I didn't waste too many people's time...
As it turns out, the second problem was 2 feet from the screen, too. I suspected it would have to do with the HTML/CSS because it was odd that only 2 out of 5 elements exhibited strange behaviour.
So, checked my code, dug out our friend FireBug, and discovered that I was hovering over another div that overlapped my rollover div. Reason being? In the CSS I had called it .panels instead of .panel, and the classname is .panel. So, it used defaults for the div... ie. 100% width...
Question is answered... "Be more careful"
Matt and Mak forced me to umpteen-check my code and sure enough I reloaded JQuery after loading another plugin and inserting my own code. Since hoverIntent modifies JQuery's hover() in order to work, re-loading JQuery mucked it up.
That solved, logic dictated I re-examine my HTML/CSS in order to investigate my fadeIn() weirdness... and sure enough, I had a typo in a class which caused some havoc.
Dumb dumb dumb... But now I can sleep.

Categories