why text() function in jquery execute before fadeOut() function - javascript

I'm trying to do the following:
Fade out a div
Change its text
Fade it in again
The problem is, step 2 is happening before step 1. Why is that happening?
Here's the code:
<p id="p">
hi!
</p>
<button onclick="foo()">
wefew
</button>
<script>
$("button").click(function (){
var item = $("#p");
item.hide("slow");
item.text("text");
item.show("slow");
})
</script>
https://jsfiddle.net/pq35yd5t/
edit:
I found that the problem is that I'm using a for loop and that the callback function only work on ht elast loop... why, again
code:
for (var i = 0; i < ob_prop.length; i++) {
if (ob_prop[i]=="tag") {
continue;
}
var item = $("#"+ob_prop[i]);
item.hide("slow", function() {
item.text(work[pointer][ob_prop[i]]).show("slow");
});
}

Because fading is an asynchronous operation.
To do what you're doing, use the callback on hide:
$("button").click(function (){
var item = $("#p");
item.hide("slow", function() {
item.text("text");
item.show("slow");
});
})
In a comment you've said:
ok i have tried it but in the original code there's a for loop and function work only at the end of the loop
The callback will have this set to the element related to the callback, so use that rather than item:
$("button").click(function (){
var item = $("#p");
item.hide("slow", function() {
$(this).text("text").show("slow");
});
})
Your latest edit has the closures in loops problem. See that question's answers for details, but one of the solutions is to use $.each (or Array.prototype.forEach if you don't have to worry about obsolete browsers like IE8):
$.each(function(index, ob) {
if (ob != "tag") {
$(ob).hide("slow", function() {
$(this).text(work[pointer][ob]).show("slow");
});
}
});

Related

Function doesn't run when I click on the button

So I have a simple JQuery code:
$(function () {
var podatoci;
var i;
$(".front").on("load", init());
$("#remove").on("click", toggleRemove());
function init() {
load();
}
function load() {
$.get("data.json", function (data, status) {
podatoci = data;
fill();
})
}
function toggleRemove() {
console.log("Yes");
$(".likse-dislikes").toggle();
}
function fill() {
for (i = 0; i < podatoci.length; i++) {
$("#container").append("<div class='wrap'><img class='img' src='"+podatoci[i].url+"'/><div class='likes-dislikes'><img class='like' src='sources/like.png'/><img class='dislike' src='sources/dislike.png'/></div></div>");
}
}
});
When I click on the button with ID: remove it runs the toggleRemove() function.
However when I run the web page and when I got to to the console when I click on the button the function doesn't run, instead it does Console.log("OK") only once presumably when the page is loaded. Can anyone please explain where is the problem and how do I fix it?
Thank you in advance!
This doesn't do what you think it does:
$("#remove").on("click", toggleRemove());
This executes toggleRemove once, when the page loads, and sets the handler to the result of that function. (Which is undefined because the function doesn't return anything.)
You want to set the handler to the function itself, not the result of the function:
$("#remove").on("click", toggleRemove);
Additionally, if your element is being added to the page after this code executes (we don't know, though the code shown implies some dynamic elements being added) then you'd need to delegate the event:
$(document).on("click", "#remove", toggleRemove);
You spelled the class name incorrectly on your remove function.
$(".likse-dislikes").toggle();
Change it to
$(".likes-dislikes").toggle();
As I can see here $(".front").on("load", init()); $("#remove").on("click", toggleRemove()); you call your call back in time when you register event listener. Try this: $(".front").on("load", init); $("#remove").on("click", toggleRemove);
You could use $scope.apply(handler)
$scope.apply(function () {
// Angular is now aware that something might of changed
$scope.changeThisForMe = true;
});

Call Function repeatedly for fade-in and fade-out JQuery

I have an array of words which I would like to fade-out and fade-in continuously. I am very new to JS and I am not able to figure out.
My code is as below:
animate_loop = function(){
var showText = ["Security","Mobile/Wireless","Cloud/Database","PC/Storage"]
$.each(showText, function(i, val) {
setTimeout(function() {
$('#animate').fadeOut("slow", function() {
$(this).text(val).fadeIn("slow");
});
}, i * 3000);
});
setInterval(function(){animate_loop();},5000)
With this code, the function loops through the array showText really fast and I was wondering if there is any other approach without a setInterval to achieve this. May be by just calling animate_loop function infinitely which I read is not advisable. So any suggestions are welcome.
other approach without a setInterval
Yes, what I've done here is use the callback's to keep a constant chain running.
Basically fadeIn / fadeOut, re-run on the fadeOut.
$(function () {
var showText = ["Security","Mobile/Wireless",
"Cloud/Database","PC/Storage"];
var
showNum = 0,
$showText = $('.showtext');
function doShow() {
$showText.text(showText[showNum]);
$showText.fadeIn('slow', function () {
$showText.fadeOut('slow', function () {
//lets make it so it wraps back to the start
showNum = (showNum + 1) % showText.length;
doShow();
});
});
}
doShow();
});
.showtext {
font-size: 24pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showtext">
</div>

javascript/jquery loop execute function after every iteration

var dagaData = ['Manok', 'Pusa', 'Daga', 'Ibon', 'Aso'];
$('#clicktest').on('click', function() {
$.each(dagaData, function(index, item) {
executeData(item);
alert(item);
});
});
function executeData(item) {
var items = $("<div></div>").text(item);
$('#pangtest').append(items);
}
Is it possible to execute the function on every iteration?
Right now when I run the code above it finished all iteration before the append happen.
That why I've put alert to see if every alert append each iteration.
Output of code above: alert('Manok'), alert('Pusa') ,alert('Daga'), alert('Ibon'), alert('Aso') executed append.
What I'm trying to achieve is alert('manok') append, alert('Pusa') append, alert('Daga') append, alert('Ibon') append, alert('Aso') append.
Thanks in advance.
In a general sense, although the DOM is updated each time you call .append() the browser won't actually repaint the screen until after the entire JS function finishes. (Though some browsers will repaint at the point when an alert is open, which is why using alert() for debugging is a bad idea: it can subtly change the behaviour in a way that calling console.log() doesn't.)
You can work around this by using a setTimeout-based pseudo-loop - in between timeouts the browser then gets a chance to repaint:
var dagaData = ['Manok', 'Pusa', 'Daga', 'Ibon', 'Aso'];
$('#clicktest').on('click', function() {
var i = 0;
(function doNext() {
var item = dagaData[i];
executeData(item);
alert(item);
if (++i < dagaData.length)
setTimeout(doNext, 5);
})();
});
function executeData(item) {
var items = $("<div></div>").text(item);
$('#pangtest').append(items);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="clicktest">Test</button>
<div id="pangtest"></div>
Or just use your original $.each() loop with the contents of the loop wrapped in a timeout, as per Bnrdo's answer. But I prefer to wait to schedule each timeout only after the previous one is done because that way the order of execution is guaranteed.
Wrap them in setTimeout
$.each(dagaData, function(index, item) {
setTimeout(function() {
executeData(item);
alert(item);
}, 1);
});

Replacing multiple <li> text simultaneously on hover using Javascript (not CSS!)

I have a requirement to change the text on hover of multiple menu items at once but I cannot use CSS and nor can I give each individual item its own CSS class. What I would like to do is when the mouse hovers anywhere over the .menu-wrapper the Javascript replaces each of the <li> item texts with the relevant replacement text.
I have a script which works perfectly for a single item:
<div class="menu-wrapper">
<ul>
<li>WORD1</li>
</ul>
</div>
Javascript:
var originalText = $('.menu-wrapper > ul > li').text();
$('.menu-wrapper').hover(function () {
var $p = $(this).find('li');
$p.fadeOut(300, function () {
$(this).text('replacement word 1').fadeIn(300);
});
}, function () {
// set original text
$(this).find('li').fadeOut(300, function () {
$(this).text(originalText).fadeIn(300);
});
});
But obviously if you add multiple <li> items it breaks because it is only storing a single .text() variable and concatenates all the entries after the first mouseout event.
I tried using a switch statement to look for the value of the .text() and change the text value accordingly but it didn't work (my Javascript is weak...).
I'd appreciate any help with this. I only have four items to replace the text of so repeating any script as necessary is not a problem. Normally I would give each one it's own class identity and use what I already have but unfortunately I can't.
Please don't suggest using CSS as I already know how to do that but for this I need to use Javascript.
I could not find this question elsewhere.
Thanks!
Main issue is first line:
var originalText = $('.menu-wrapper > ul > li').text();
This will get all text from all elements in the collection:
What you could do is store that text on each element using jQuery data() by looping over the elements and dealing with instances:
$('.menu-wrapper > ul > li').each(function(){
$(this).data('original', $(this).text());
});
Then in mouseout part of hover read the previously stored text using data() again
$(this).find('li').fadeOut(300, function () {
var originalText = $(this).data('original');
$(this).text(originalText).fadeIn(300);
});
Several options for the new text:
Put it in markup as data attribute
<li data-alt_text="alternate word">
Then within mousenter callback of hover:
$p.fadeOut(300, function () {
$(this).text($(this).data('alt_text')).fadeIn(300);
});
Or put in array and use first loop to add the array data to element
var words=['W1','W2','W3'];
// first argument of "each" is "index"
$('.menu-wrapper > ul > li').each(function(index){
$(this).data(
{
'alt_text': words[index],
'original', $(this).text()
}
);
});
You can make use of javascripts ability to assign any property to an object (element) to store the original text instead of storing it in a single variable (or use jquery data functionality to do the same)
$('.menu-wrapper li').hover(function () {
$(this).fadeOut(300, function () {
this.originalText = $(this).text();
$(this).text('replacement word 1').fadeIn(300);
});
}, function () {
// set original text
$(this).fadeOut(300, function () {
$(this).text(this.originalText).fadeIn(300);
});
});
fiddle
For this to work, instead of binding to the .menu-wrapper div directly, you can use .menu-wrapper li to bind to the individual li elements inside the div. Afterwards the orignal text can be stored before changing it. The same can be done beforehand, storing all values, the advantage of this way is that you always store the latest value, in case the text is dynamically altered after startup.
To couple the replacement texts to the li elements, without altering the html safest would be to couple the replacement to the text. Easiest is an indexed based solution:
var replacements = ['replacement Word1', 'for word2' , 'third time\'s a charm'];
$('.menu-wrapper li').hover(function () {
var $this= $(this);
$this.fadeOut(300, function () {
$this.data('originalText', $this.text()).
text(replacements[$this.index()]).fadeIn(300);
});
}, function () {
// set original text
$(this).fadeOut(300, function () {
$(this).text($(this).data('originalText')).fadeIn(300);
});
});
fiddle
For completeness sake, this would be an alternative while using the li text (provided the text can be used as a property):
var replacements ={
WORD1 : 'replacement Word1',
WORD2 : 'for word2',
WORD3: 'third time\'s a charm'
};
$('.menu-wrapper li').hover(function () {
var $this= $(this);
$this.fadeOut(300, function () {
$this.data('originalText', $this.text()).
text(replacements[$this.text()]).fadeIn(300);
});
}, function () {
// set original text
$(this).fadeOut(300, function () {
$(this).text($(this).data('originalText')).fadeIn(300);
});
});
fiddle
Here's a short and simple solution to your problem:
var originalText;
$('.menu-wrapper').hover(function () {
var $p = $(this).find('li');
$p.fadeOut(300, function () {
this.originalText = $(this).text(); // STORES VALUE BEFORE REPLACEMENT
$(this).text('replacement word 1').fadeIn(300);
});
}, function () {
$(this).find('li').fadeOut(300, function () {
$(this).text(this.originalText).fadeIn(300);
});
});
Just store the value of that element in originalText before replacing it.
We can use two arrays to store Original text and New text. And then use $.each to loop through each of the lis and use their index to replace the text.
HTML :
<div class="menu-wrapper">
<ul>
<li>WORD1</li>
<li>WORD2</li>
<li>WORD3</li>
</ul>
</div>
jQuery :
var originaltext = ['Word1','Word2','Word3'];
var newText = ['New text1','New text2','New text3'];
$('.menu-wrapper').hover(function () {
$('.menu-wrapper li').each(function(i){
$this = $(this);
$this.html(newText[i])
});
}, function(){
$('.menu-wrapper li').each(function(i){
$this = $(this);
$this.html(originaltext[i])
});
});
jsfiddle
Since all of the other answers here use jQuery, I'll add one done with vanilla js.
To do this, we're going to need to use a javascript closure. This is used so that on completion of the fade-out, we have (a) the element just faded and (b) which is far more important, an index into the originalStrings array. (B) is the more important here, because the target element is something the animate code already has - we could easily pass the original element to the callback function. However, we really need the index or the string that corresponds to each element. The closure gives a means to do so.
The following code will fade-out all/any matching elements and then perform a fade-in after changing the text.
Using the equations found here: Math: Ease In, ease Out a displacement using Hermite curve with time constraint we can then set about making some code that will perform a smooth fade/move/scale pitch/volume slide etc, etc. I did this an ended up a few functions that facilitate simple animations. I've included minified versions of them below, for an all-in-one complete solution that relies on no other resources.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
document.getElementById('goBtn').addEventListener('click', onButtonClick, false);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// animation stuff
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function cubicHermite(a,b,d,e,c){var g=a*a,f=g*a;return(2*f-3*g+1)*b+(f-2*g+a)*e+(-2*f+3*g)*d+(f-g)*c}
function interp(a,b,d,e,c){var g,f;f=e/(a/2+b+d/2);g=f*a/2;f*=b;return c<=a?cubicHermite(c/a,0,g,0,f/b*a):c<=a+b?g+f*(c-a)/b:cubicHermite((c-a-b)/d,g+f,e,f/b*d,0)}
function linear(a){return a}
function cubic(a){return interp(0.35,0.3,0.35,1,a)}
function doAnimStep(a,b,d,e,c){a<=b?(setTimeout(function(){doAnimStep(a,b,d,e,c)},d),e(a/b),a++):void 0!=c&&null!=c&&c()}
function doAnim3(totalMs, stepCallbackFunc, doneCallbackFunc)
{
var stepDelay = 1000 / 60.0; // set anim to 60 fps
var numSteps = (totalMs / stepDelay)>>0;
setTimeout( doAnim3TimeoutCallback, stepDelay );
function doAnim3TimeoutCallback()
{
doAnimStep(0, numSteps, stepDelay, stepCallbackFunc, doneCallbackFunc);
};
}
function animFadeOut(elem, callback){ doAnim3(500,function(raw){elem.style.opacity=1-cubic(raw)},callback); }
function animFadeIn(elem, callback) { doAnim3(500,function(raw){elem.style.opacity=cubic(raw)},callback); }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var replacementStrings = [ "replacement 1", "I'm next", "mee too", "fourth item" ];
function onButtonClick(evt)
{
var originalStrings = [];
var targetLiElems = document.querySelectorAll('.menu-wrapper > ul > li');
for (var i=0,n=targetLiElems.length;i<n;i++)
{
var curElem = targetLiElems[i];
originalStrings.push(curElem.innerText);
animFadeOut(curElem, createFunc(i) );
}
function createFunc(i)
{
return function(){ var curElem = targetLiElems[i]; curElem.innerText = replacementStrings[i]; animFadeIn(curElem); };
}
}
</script>
<style>
</style>
</head>
<body>
<button id='goBtn'>Change the text</button>
<div class="menu-wrapper">
<ul>
<li>WORD1</li>
<li>WORD2</li>
<li>WORD3</li>
<li>WORD4</li>
</ul>
</div>
</body>
</html>

how to do jquery once fade out has finished?

I'm trying to fade out a div on a click but also change some css values.
the issue im having is that the values change while the fade out is happening (too early). I need the values to change once the fade out has finished:
<script type="text/javascript">
$('#r_text').click(function() {
$(".box1_d").fadeOut();
$(".box1_c").css("top","0px");
});
</script>
Now when i run that, everything works but just not exactly how i'd like it.. I need the css values to be changed once the fadeout has finished, not while it's still happening.
is this possible?
if so, any ideas how?
thank you.
Use a callback function to modify the .css() as the second parameter to fadeOut(). It will fire when the fade completes.
<script type="text/javascript">
var fadeTime = 500;
$('#r_text').click(function() {
$(".box1_d").fadeOut(fadeTime, function() {
$(".box1_c").css("top","0px");
});
});
</script>
Provided you use jQuery version >= 1.5, you can/should utilize the Deferred object instead of using the callback parameter:
$('#r_text').click((function () {
var animations = {
initial: function () {
return $(".box1_d").fadeOut(1500);
},
following: function () {
return $(".box1_c").css("top","0px").animate({fontSize: '150%'});
},
onDone: function () {
alert('DONE!');
}
};
return function(e) {
$.when(animations.initial())
.pipe(animations.following)
.done(animations.onDone);
e.preventDefault();
};
}()));
JsFiddle of it in action: http://jsfiddle.net/wGcgS/2/

Categories