how to traverse a loop in javascript - javascript

I've three boxes ,each one fades in, shakes then fades out.
The ID of each one reserved in an array and a loop traverses them,the loop works correctly but just shows the first item!.
I've checked the javascript with different ways using for loop,delay instead of setTimeout
.I've also tried to add the boxes in html not in js file
(if it casued any problems!!!!!!!!)
Here is my code:
http://jsfiddle.net/#&togetherjs=QLRAbwHOR7
could any one help me please???!!
$(document).ready(function(){
var imgID= ['red','green','blue'];
$.each(imgID, function(i) {
$(".image").append('<div class="box"fid="'+i+'">'+imgID[i]+'</div>');
$('#'+i).fadeIn(500);
setTimeout(function(){
$('#'+i).effect( "shake",{times:5}, 1000 ).fadeOut(500);
}, 1000);
alert("ID: "+i);
});
});

Based on the code in the question (not the jsfiddle link) I think the problem is on this line
$(".image").append('<div class="box"fid="'+i+'">'+imgID[i]+'</div>');
^
should be
$(".image").append('<div class="box" id="'+i+'">'+imgID[i]+'</div>');
^ remove the 'f'
here is my fiddle results
http://jsfiddle.net/jasrus/ZqayT/
Update Also make sure that you include jQueryUI because effect is not part of the jquery library

Related

Separate pieces of Javascript in the same file

I have the following code inside a file called additional.js for a WordPress website I'm working on:
// Fade in for news posts
jQuery(".elementor-post").each(function(i) {
jQuery(this).delay(250 * i).fadeIn(1000);
});
// Alphabetical Filter for Products
var $boxes = $('.elementor-posts-container > .elementor-post');
var $btns = $('.alphabet-btn').click(function() {
var id = this.id;
if (id == 'all') {
$boxes.show()
} else {
$boxes.hide().filter(function() {
var re = new RegExp('^' + id, 'i');
return re.test($(this).text().trim());
}).show()
}
$btns.removeClass('alphabet-active');
$(this).addClass('alphabet-active');
})
The first part is a simple timed fade in for my blog posts and the second part is the js for an alphabetical filter on my products page.
Currently, the alphabetical filter is acting strangely. If you go here and click on B, for example, http://staging.morningsidepharm.com/products/generic-medicines/ if filters and leave the product beginning with B but then it fades in all of the other products after this - This is only on the initial click... after that, when you click around it seems to be acting as it should.
If I remove the first bit of code from the top of my file:
jQuery(".elementor-post").each(function(i) {
jQuery(this).delay(250 * i).fadeIn(1000);
});
Everything in the alphabet search works correctly, even on the initial click.
Which makes me believe there is something conflicting in the two bits of code.
Do I need to END the first bit of code somehow? or I there something else conflicting here?
I tried separating them and putting them in different .js files, but I guess that doesn't work because they both are still fired when the page loads.
Any help would be greatly appreciated, I'm so close! :)
In the first part you use a syntax of JQuery() and in the second you use another $() test by changing JQuery() by $() in the first part of your code, maybe that makes conflict.
Ok, I found the issue.
In the first bit of code, I'm targeting the .elementor-post selector without being specific to which .elementor-post I want to target. This meant it would affect the div .elementor-post sitewide.
Adding a container class and changing the top part of the code to the following fixed things:
// Fade in for news posts
jQuery(".fade-in-post-container .elementor-post").each(function(i) {
jQuery(this).delay(250 * i).fadeIn(1000);
});

Switch HTML content of div with another piece of HTML without fading out to white first using jQuery

I'm looking for a way to fade from one piece of HTML in a div to another piece of HTML without fading out to white (to the background color of the div) first like i'm doing in this example:
The positionNumber variable is just an int with the number (e.g. 3).
function changeContent(positionNumber) {
$('.banner-content-wrapper').fadeOut('fast', function() {
var contentHtml = $('.slidercontent#' + positionNumber).html();
$('.banner-content-wrapper').hide().fadeIn(1000).html(contentHtml);
});
}
This example does the exact same by fading to white first but this is not what I'm lookig for:
Why doesn't jquery fadeIn() work with .html()?
I want to fade directly from one piece of HTML to another. I haven't been able to find any example on Stack Overflow that shows how to do exact that. I know this is not valid code but it's something like this I'm looking for:
$('.banner-content-wrapper').fadeToHtml(contentHtml);
How can I fade directly?
why use fadeOut/fadeIn - why not hide/show
function changeContent(positionNumber) {
$('.banner-content-wrapper').hide('fast', function() {
var contentHtml = $('.slidercontent#' + positionNumber).html();
$('.banner-content-wrapper').hide().html(contentHtml).show();
});
}
I have not tested this - just a suggestion based on the example you referenced
I don't think you should use fade. Try to use Replace.
http://api.jquery.com/replacewith/

Toggle on div show/hide

I know there are several questions/solutions to this problem, and I am looking for a combination of two simple solutions(I am not a coder, just a copy/paste/manipulator) so here goes: I need a script which involves a button that toggles show/hide divs on top of a large imagemap, whose function is to turn on/off labels contained within each div. As the imagemap is large and contains groups, I am looking for a way to loop the following functional script:
$(document).ready(function() {
$(".hide").click(function() {
$(this).siblings(".hideShow").hide();
});
$(".show").click(function() {
$(this).siblings(".hideShow").show();
});
});
The loop is needed as I will have well over 200 labels to toggle(removing them will clear some visual space). The html above lists two buttons, whereas I need only one which toggles between the two, like the one behind this jquery bit:
var toggleState = false;
$('.show').click(function() {
$(".text").toggle();
$(this).toggleClass('hide').attr('title', toggleState ? 'Show All' : 'Hide All');
toggleState = !toggleState;
})
The former jfiddle found here: http://jsfiddle.net/MztAm/
The latter here: http://jsfiddle.net/y8ZTj/1/
Actually, as the latter script is more desireable, is it possible to turn it into a loop, replacing ".text" to accomodate many instances?
The best I could come up with: http://jsfiddle.net/qmv3dmya/ though I need a new instant of the jquery piece for every grouping. But I'll end up putting the series in a separate *.js sheet to be referenced by the main page.
It is possible that I don't understand your question correctly, but if I do, then perhaps this information will be helpful:
(1) You do not need a loop. With jQuery, selecting all DIVs with class="text" looks like this:
$('.show').click(function() {
$(".text").toggle();
});
(2) This bit: $(".text") creates an object that contains a list of all DIVs that have class="text"
(3) This bit: .toggle() applies that method to each element contained in $('.text')
Therefore, all elements with class="text" will be toggled visible/invisible as a group. No need for a loop.
jsFiddle Demo
If you did need a loop, you could use .each(), like this:
$('.text').each(function(){
// Whatever you do in here will be done once to each DIV
// (or other element) contained in the object ("list") of
// all elements with `class="text"`
});
You can you siblings function see below.
Jquery:
var toggleState = false;
$('.show').click(function() {
$(this).siblings(".text").toggle();
$(this).toggleClass('hide').attr('title', toggleState ? 'Show All' : 'Hide All');
toggleState = !toggleState;
});
DEMO

Giving user 2nd attempt

In my spelling game there is a grid with words in to spell. The user is given a highlighted area in the grid and some clues like a picture and a sound of a word like "cat" for example.
The user then is supposed to click the corresponding letters on the side of the grid to achieve the correct answer.
If the user correctly spells the word, the word fades out to show a section of the image behind. The aim of the game is to spell all the words correctly and reveal the the whole image
If the user gets the spelling of a word wrong, there is a style applied to the word that makes it glow red, this should then fade after 2 seconds and he/she should be given another attempt to try to spell the word.
Currently when a word is spelt incorrectly the style appears to make the word glow red, but it does not go after 2 seconds and the user is not given another shot at the word.
I have used this line of code to get rid of the style's after 2 seconds...
$('.drop-box.spellword').removeClass('wordglow wordglow3 wordglow4', "2000");
For some reason it doesn't work
The script that adds the styles is here...
if (!$('.drop-box.spellword:not(.occupied)').length) {
var wordIsCorrect = 0;
$('.drop-box.spellword').each(function() {
if ($(this).attr("data-letter") == $(this).find("div").attr("data-letter")) {
wordIsCorrect++;
}
});
console.log(wordIsCorrect);
console.log($('.drop-box.spellword').length);
if ($('.drop-box.spellword').length == wordIsCorrect) {
$('.drop-box.spellword').addClass('wordglow2');
$(right).val('Well Done!');
$(right).show();
audioS.play();
$('.counter').html(completeWords + '/6').show();
$(wrong).hide();
$('.minibutton').prop('disabled', false);
} else {
$('.drop-box.spellword').addClass("wordglow4").css('color', 'transparent');
$(wrong).val('Try Again');
$('.minibutton').prop('disabled');
$(wrong).show();
audioF.play();
$('.counter').html(completeWords + '/6').show();
$(right).hide();
$('.minibutton').prop('disabled', true);
}
To give the user another attempt I thought you may use something like this..
$('.drop-box.spellword').splice(0, $('.drop-box.spellword').length);
You have to use javascript's setTimeout function, for jQuery's removeClass doesn't accept an argument for timeouts.
Also, removeClass only removes one class at the time, so you have to chain them.
try replacing this:
$('.drop-box.spellword').removeClass('wordglow wordglow3 wordglow4', "2000");
for this:
setInterval(
function(){
$('.drop-box.spellword').removeClass('wordglow').removeClass('wordglow3').removeClass('wordglow4');
}, 2000
);
To remove the class after 2 seconds, use this:
setTimeout(function(){
$('.drop-box.spellword').removeClass('wordglow wordglow3 wordglow4')
},2000)
removeClass doesn't accept any argument for a delay before removing a class.
I'm not sure what you're trying to do with the splice, but one error I can see is that you forgot a $ before ('.drop-box.spellword') inside the splice() call.
jQuery's removeClass doesn't support passing a second parameter to be considered as a timer, but you can do this manually using setTimeout():
setTimeout(function() {
$('.drop-box.spellword').removeClass('wordglow wordglow3 wordglow4');
}, 2000);
As for giving the user another attempt, why are you using splice()? Isn't each element with class drop-box.spellword a text input with individual strings? In that case you can use $('.drop-box.spellword').val('') to clear all inputs of that class.
Edit:
To remove the classes from the other children modify it to something like this:
$('.drop-box.spellword').removeClass('wordglow4');
$('.drop-box.spellword').children('.ui-widget-content').removeClass('wordglow')
The jsFiddle is really large so I'm not sure where wordglow3 gets applied, but the principle is the same, find the element and removeClass() from it, all in your timed function.

Alternative to jQuery replaceAll()?

I have some code that removes a tr from a dynamically built table as a jQuery object (each tr has a unique id: trid):
tri = $("#"+trid+"");
var newrow = '<tr id="newr"><td colspan="4" align="center"><div id="nrow"> </div></td></tr>';
tri.after(newrow);
tri.detach();
I then put a form in the div 'nrow' using innerHTML... There's a jQuery ui datepicker in the form that works this first time.
When the form is cancelled I put the list back to the way it was:
setTimeout("tri.replaceAll( $('#newr') )", 400);
This all works beautifully, except that it kills the jquery ui datepicker in the form if I try to edit that (or any) row after that. I've trouble shot it down to being the replaceAll line. If I take that out and replace the list by building it again it works just fine (it's not the timeout either).
So is there another way to replace the tr 'newr' with the jquery object 'tri' without using replaceAll (replaceWith doesn't work either)?
EDIT:
OK so this is how I move the form from the div elsewhere on the page:
eP = $('#eP');
eP.replaceAll( $('#nrow') );
$("#editPast").show('blind','',500,'');
eP contains the hidden div editPast...
then in the cancel function I put eP back:
setTimeout(function() {eP.appendTo($('#ePreplace')); }, 500); (thanks adeneo!)
before I tri.replaceAll, though with the setTimeout it happens after...
So I guess my problem is that eP doesn't carry the datepicker state after it's been used in #nrow, just the html.
FIXED!
changed eP.appendTo to $('#eP').appendTo so that it takes it from the dom instead of the original variable. Oops! Thanks for making me re-think this with your just detach() comment!
FIXED!
changed eP.appendTo to $('#eP').appendTo so that it takes it from the dom instead of the original variable. Oops! Thanks adeneo for making me re-think this with your 'just detach()' comment!
Thanks NiftyDude for suggesting I do this too...

Categories