adding class to array elements through loop - javascript

I need the loop that checks input fields from 'inputs' array, and if there are empty fields, special dialog need to be displayed near them, and after the dialog is displayed I need class 'style' to be added to the input field near which the dialog was displayed, then dialog should go to the next emppty field and add class 'style' to it. And so on until all empty inputs have class 'style'.
The problem is, in my loop after the dialog is displayed class 'style' is added only to the last element from the array, but it should be added to every empty element with delays in between.
This is my loop, but as I said it is not working properly:
for(i=0;i<inputs.length;i++){
var now = inputs[i];
var top = inputs[i].attr('top');
if(!now.val()){
if(dialog.css('display')=='none'){now.addClass('style');dialog.css('top',top).fadeIn(200);}
else{dialog.delay(300).animate({"top": top}, 500, function(){now.addClass('style');});
}else{now.removeClass('style');}}
P.S. Sorry for my English.

This is happening because the function that is calling 'addClass' is happening after the 300 millisecond animation. By that time, the value of the 'i' variable has changed because the for loop will continue to run.
You may just be able to have the 'now.addClass' call before the 'animate' and delay. Otherwise, you will have to break the loop and continue after the animation is complete to prevent the variable from being overwritten.
Here is an example of what I was talking about. The code below will process 1 input at a time and not continue to the next until the current one is finished processing (this code has not been tested):
var offset = -1;
var inputs = (something goes here)
iterateInputs();
function iterateInputs()
{
offset++;
if (typeof inputs[offset] != 'undefined')
{
eachInput();
}
else
{
// all done!
}
}
function eachInput()
{
var now = inputs[offset];
var top = inputs[offset].attr('top');
if (!now.val())
{
if (dialog.css('display')=='none')
{
now.addClass('style');
dialog.css('top', top).fadeIn(200, function(){
iterateInputs();
});
}
else
{
dialog.delay(300).animate({"top": top}, 500, function(){
now.addClass('style');
iterateInputs();
});
}
}
else
{
now.removeClass('style');
iterateInputs();
}
}

Related

dont wait until function finishes to run another function

Hello I am creating this script where I create a post request that adds an item to cart and selects the size all in the backend.
As it runs it opens up a loading html and I wanted to have the current item that is being added's info added into a table in the html page.
Im not sure if this is the most efficent and fast method (please let me know if there is a better way) but what I did was I create a listener on the html/js page and send a message from the background.js page that is doing the work to that js page that is listening for the message.
What it does is that It finds the item so it sends a message of the item name, then it finds the items proper color and sends a message of the color selected, then it finds the size and selects the proper size. here is the code:
chrome.runtime.sendMessage({ carting: true, status: {
status_item: (item[0]) //item name
} });
//carting code(irrelevant to this issue)
chrome.runtime.sendMessage({ carting: true, status: {
status_color: (item[1]) //item color
} });
//more irrelevent carting code
chrome.runtime.sendMessage({ carting: true, status: {
status_size: (size_text.text) // size
} });
this is what I had in the listener page:
chrome.runtime.onMessage.addListener(function(message, sender) {
if (!message.carting) return;
var Status = message.status;
$(function() {
$("#tasks_table").append('<tr>'
+'<td>'+item+'</td>'
+'<td>'+color+'</td>'
+'<td>'+size+'</td>'
+'</tr>');
}
})
The problem with it was is that during the carting process when it yet hasn't found the color it would just constantly add undefined into the table so I found a solution to that issue by using functions:
function waitForItem(item) {
if (typeof item !== "undefined") {
$("#tasks_table").append('<tr>'+'<td>'+item+'</td>');
} else {
setTimeout(waitForItem, 10);
}
}
function waitForColor(color) {
if (typeof color !== "undefined") {
$("#tasks_table").append('<td>'+color+'</td>');
} else {
setTimeout(waitForColor, 10);
}
}
function waitForSize(size) {
if (typeof size !== "undefined") {
$("#tasks_table").append('<td>'+size+'</td>'+'</tr>');
} else {
setTimeout(waitForSize, 10);
}
}
waitForItem(item);
waitForColor(color);
waitForSize(size);
Now this did work it stopped adding the undefined into the table but now the problem is that it runs the first item function until it is completly done and then so on with each function.
When I have two items it adds the item name for the first item into the table then waits until the second item name is found and adds it too then proceeds to add all the color and the sizes. The problem with this is that my background page works in a loop. It finds the first item, then its color, then its size, then it goes onto the next item, its color, and its size.
So when It finds the first item and then the second item it adds all the rest of the color and size right at the same time. Which I don't want.
I want it to add the info into the table the same way the background page runs so the user can see how smoothly and fast it runs.

Switching style between two elements on photo gallery change

So I have a photo gallery on my front page that switches between two images; each image links to a different page. Now, beside that gallery I have two links that go to the same two pages. The idea is that when image A is showing, side-link A should be highlighted with a border. The issue I keep running into is that once I get either side-link to be highlighted, I don't really know how to get it unhighlighted. Instead of switching with the images, they just stay highlighted.
var debugLink = "#firstLink";
function displayNextImage()
{
index++;
if(index >= indexgalpics.length)
{
index=0;
}
//---this is where I set the var debugLink which is
// supposed to carry the selected linke
if(index == 0)
{
console.log("first link selected");
//---when image A is showing, top side-link should be highlighted
//---ok so we know this much works, it seems these double equal
// signs are very important here.
//---makeActive();
//---but once makeActive() is called here, it makes the first link
// active for the entire time.
//---we can't put the entire style code here because same as before,
// it just keeps the link highlighted forever
debugLink = "#firstLink";
//---ok so i can set a var at top to a value in the makeActive() function,
// but i think the way JS works highlights either one forever
debugLink = "#firstLink";
}
else if(index == 1)
{
console.log("second link should be selected");
//---when image B is showing, bottom side-link should be highlighted
debugLink = "#secondLink";
}
showImg();
}
function makeActive()
{
var activeLink = document.querySelector(debugLink);
//---adds style to the debugLink
}
The function makeActive() is called in the function showImg(), and the function displayNextImage() is called in another function that sets the timer.
I changed your approach a little bit by using a boolean for the index, because you seem to only need two states.
Here is a revised version:
Note: In this code, I've used custom-made functions to make the code easier to read. I created hasClass(el,class), addClass(el,class), removeClass(el,class), toggleClass(el,class,bool). You can find them in the final JS Fiddle.
// Register the link elements
var links = {
true : document.getElementById('firstLink'),
false : document.getElementById('secondLink')
},
// Keep track of selected link (replaces your 'index')
leftLinkActive = false,
// Just so you don't go get it every time
gallery = document.getElementById('gallery');
// Let's trigger the gallery
displayNextImage();
// We'll change the active link and show the correct image
function displayNextImage(){
leftLinkActive = !leftLinkActive;
if(leftLinkActive){ console.log("first link selected"); }
else{ console.log("second link selected"); }
makeActive();
showImg();
// Let's do that again in 2 seconds
setTimeout(displayNextImage,2000);
}
// Add / remove the active class
function makeActive(){
addClass( links[ leftLinkActive ], 'active-class');
removeClass( links[ !leftLinkActive ], 'active-class');
}
// Change the image with a small fadeOut transition
function showImg(){
addClass(gallery,'fadeOut');
setTimeout(function(){
// Here we switch from img1 and img2
gallery.style.backgroundImage = 'url('+(leftLinkActive?'im1.jpg':'im2.jpg')+')';
removeClass(gallery,'fadeOut');
},200);
}
JS Fiddle Demo

JavaScript textfield validation: sending focus back

I am using JQuery and JavaScript for an input form for time values, and I can't make JavaScript to provide the intended reaction to incorrect input format.
What do I do wrong...?
I have a set of 3 text inputs with class "azeit" (and under these a number of others of class "projekt"). All are used to input time values. As soon as the user exits the field I validate the format, do a calculation with it and display the result of this in a field with id "summe1". This works. If the format is incorrect, I display an alert and what I want to do is return the focus to the field after emptying it. However, the focus never gets returned (although it will get emptied all right). This is it:
var kalkuliere_azeit = function(e) {
var anf = $("#anfang");
var ende = $("#ende");
var pause = $("#pause");
var dauer_in_min = 0;
var ungueltiges = null;
if (nonempty(anf.val(), ende.val()), pause.val()))
{
if (!is_valid_date(make_date(anf.val()))){
ungueltiges = anf;
};
if (!is_valid_date(make_date(ende.val()))){
ungueltiges = ende;
};
if (!is_valid_date(make_date(pause.val()))){
ungueltiges = pause;
};
if (ungueltiges)
{
alert("invalid time"); //This is where I am stuck
ungueltiges.val("");
ungueltiges.focus();
}
else {
dauer_in_min = hourstring_to_min(ende.val())
- hourstring_to_min(anf.val())
- hourstring_to_min(pause.val());
$("#summe1").text(min_to_hhmm(dauer_in_min));
};
};
};
....
$(document).ready(function() {
$(".projekt").change( kalkuliere_summe);
$(".azeit").focusout(kalkuliere_azeit);
});
The fields with the class "projekt" are below those with the class "azeit" so they'll get the focus when the user leaves the third field of class "azeit".
I apologize for supplying incomplete source code. I hope someone can see what's wrong.
One point I'd like to mention is that I tried binding the handler to onblur and onfocus as well. When I bind it to onfocus the focus does get reset to the field, but the last field the user enters will not update the field $("#summe1") correctly (because this would need focusing another field of the same class).
Im not sure whats wrong with your code but one way of doing it would be to put the focus into a function.
So ...
function focusIt()
{
var mytext = document.getElementById("divId");
mytext.val("");
mytext.focus();
}
And call it from the if/else statement ...
if (ungueltiges)
{
alert("invalid time");
focusIt()
}

BB Code Parser (in formatting phase) with jQuery jammed due to messed up loops most likely

Greetings everyone,
I'm making a BB Code Parser but I'm stuck on the JavaScript front. I'm using jQuery and the caret library for noting selections in a text field. When someone selects a piece of text a div with formatting options will appear.
I have two issues.
Issue 1. How can I make this work for multiple textfields? I'm drawing a blank as it currently will detect the textfield correctly until it enters the
$("#BBtoolBox a").mousedown(function() { }
loop. After entering it will start listing one field after another in a random pattern in my eyes.
!!! MAIN Issue 2. I'm guessing this is the main reason for issue 1 as well. When I press a formatting option it will work on the first action but not the ones afterwards. It keeps duplicating the variable parsed. (if I only keep to one field it will never print in the second)
Issue 3 If you find anything especially ugly in the code, please tell me how to improve myself.
I appriciate all help I can get. Thanks in advance
$(document).ready(function() {
BBCP();
});
function BBCP(el) {
if(!el) { el = "textarea"; }
// Stores the cursor position of selection start
$(el).mousedown(function(e) {
coordX = e.pageX;
coordY = e.pageY;
// Event of selection finish by using keyboard
}).keyup(function() {
BBtoolBox(this, coordX, coordY);
// Event of selection finish by using mouse
}).mouseup(function() {
BBtoolBox(this, coordX, coordY);
// Event of field unfocus
}).blur(function() {
$("#BBtoolBox").hide();
});
}
function BBtoolBox(el, coordX, coordY) {
// Variable containing the selected text by Caret
selection = $(el).caret().text;
// Ignore the request if no text is selected
if(selection.length == 0) {
$("#BBtoolBox").hide();
return;
}
// Print the toolbox
if(!document.getElementById("BBtoolBox")) {
$(el).before("<div id=\"BBtoolBox\" style=\"left: "+ ( coordX + 5 ) +"px; top: "+ ( coordY - 30 ) +"px;\"></div>");
// List of actions
$("#BBtoolBox").append("<img src=\"./icons/text_bold.png\" alt=\"B\" title=\"Bold\" />");
$("#BBtoolBox").append("<img src=\"./icons/text_italic.png\" alt=\"I\" title=\"Italic\" />");
} else {
$("#BBtoolBox").css({'left': (coordX + 3) +'px', 'top': (coordY - 30) +'px'}).show();
}
// Parse the text according to the action requsted
$("#BBtoolBox a").mousedown(function() {
switch($(this).children(":first").attr("alt"))
{
case "B": // bold
parsed = "[b]"+ selection +"[/b]";
break;
case "I": // italic
parsed = "[i]"+ selection +"[/i]";
break;
}
// Changes the field value by replacing the selection with the variable parsed
$(el).val($(el).caret().replace(parsed));
$("#BBtoolBox").hide();
return false;
});
}
This line: $("#BBtoolBox a").mousedown(function() attaches a function to the links. However, this line is run multiple times, and each time it runs it attaches another function to the links, leaving you with duplicated text.
An optimal solution is to use a plugin, for example (the first one I found): http://urlvars.com/code/example/19/using-jquery-bbcode-editor (demo)

IE javascript error - possibly related to setAttribute?

I am using Safalra's javascript to create a collapsible list. The script works across several browsers with no problem. However, when I apply the javascript to my own list, it fails to act as expected when I use IE (I'm using 7 at the moment). It simply writes the list, without the expand and contract images.
I copied the Safalra's javascript precisely, so I assume the error must be in my own list. This is how I generated my list:
<body onLoad="makeCollapsible(document.getElementById('libguides'));">
<ul id="libguides">
<script type="text/javascript" src="http://api.libguides.com/api_subjects.php?iid=54&more=false&format=js&guides=true&break=li"></script>
</ul>
(Yes, I do close the body tag eventually.) When I run this in IE, it tells me that line 48 is causing the problem, which appears to be:
node.onclick=createToggleFunction(node,list);
Here's the entire function:
function makeCollapsible(listElement){
// removed list item bullets and the sapce they occupy
listElement.style.listStyle='none';
listElement.style.marginLeft='0';
listElement.style.paddingLeft='0';
// loop over all child elements of the list
var child=listElement.firstChild;
while (child!=null){
// only process li elements (and not text elements)
if (child.nodeType==1){
// build a list of child ol and ul elements and hide them
var list=new Array();
var grandchild=child.firstChild;
while (grandchild!=null){
if (grandchild.tagName=='OL' || grandchild.tagName=='UL'){
grandchild.style.display='none';
list.push(grandchild);
}
grandchild=grandchild.nextSibling;
}
// add toggle buttons
var node=document.createElement('img');
node.setAttribute('src',CLOSED_IMAGE);
node.setAttribute('class','collapsibleClosed');
node.onclick=createToggleFunction(node,list);
child.insertBefore(node,child.firstChild);
}
I confess I'm too much of a javascript novice to understand why that particular line of code is causing the error. I looked at some of the other questions here, and was wondering if it might be a problem with setAttribute?
Thanks in advance.
Edited to add:
Here's the code for the createToggleFunction function. The whole of the script is just these two functions (plus declaring variables for the images).
function createToggleFunction(toggleElement,sublistElements){
return function(){
// toggle status of toggle gadget
if (toggleElement.getAttribute('class')=='collapsibleClosed'){
toggleElement.setAttribute('class','collapsibleOpen');
toggleElement.setAttribute('src',OPEN_IMAGE);
}else{
toggleElement.setAttribute('class','collapsibleClosed');
toggleElement.setAttribute('src',CLOSED_IMAGE);
}
// toggle display of sublists
for (var i=0;i<sublistElements.length;i++){
sublistElements[i].style.display=
(sublistElements[i].style.display=='block')?'none':'block';
}
}
}
Edited to add (again):
Per David's suggestion, I changed all instances of setAttribute & getAttribute...but clearly I did something wrong. IE is breaking at the 1st line (which is simply the doctype declaration) and at line 49, which is the same line of code where it was breaking before:
node.onclick=createToggleFunction(node,list);
Here's the first function as written now:
function makeCollapsible(listElement){
// removed list item bullets and the sapce they occupy
listElement.style.listStyle='none';
listElement.style.marginLeft='0';
listElement.style.paddingLeft='0';
// loop over all child elements of the list
var child=listElement.firstChild;
while (child!=null){
// only process li elements (and not text elements)
if (child.nodeType==1){
// build a list of child ol and ul elements and hide them
var list=new Array();
var grandchild=child.firstChild;
while (grandchild!=null){
if (grandchild.tagName=='OL' || grandchild.tagName=='UL'){
grandchild.style.display='none';
list.push(grandchild);
}
grandchild=grandchild.nextSibling;
}
// add toggle buttons
var node=document.createElement('img');
node.src = CLOSED_IMAGE;
node.className = 'collapsibleClosed';
node.onclick=createToggleFunction(node,list);
child.insertBefore(node,child.firstChild);
}
child=child.nextSibling;
}
}
And here's the second function:
function createToggleFunction(toggleElement,sublistElements){
return function(){
// toggle status of toggle gadget
// Use foo.className = 'bar'; instead of foo.setAttribute('class', 'bar');
if (toggleElement.className == 'collapsibleClosed') {
toggleElement.className = 'collapsibleOpen';
toggleElement.src = OPEN_IMAGE;
} else {
toggleElement.className = 'collapsibleClosed';
toggleElement.src = CLOSED_IMAGE;
}
// toggle display of sublists
for (var i=0;i<sublistElements.length;i++){
sublistElements[i].style.display=
(sublistElements[i].style.display=='block')?'none':'block';
}
}
}
Internet Explorer (until version 8, and then only in best standards mode) has a very broken implementation of setAttribute and getAttribute.
It effectively looks something like this:
function setAttribute(attribute, value) {
this[attribute] = value;
function getAttribute(attribute, value) {
return this[attribute];
}
This works fine iif the attribute name matches the property name, and the property takes a string value.
This isn't the case for the class attribute, where the matching property is className.
Use foo.className = 'bar'; instead of foo.setAttribute('class', 'bar');
node.onclick=createToggleFunction(node,list);
That is probably not what you want. Does createToggleFunction return a function? If it doesn't, then I bet you meant this:
node.onClick = function() { createToggleFunction(node, list); };
If my guess is right then the way you have it will set the onClick event handler to be the result of createToggleFunction, not a function like it needs to be.

Categories

Resources