Get current index of jCarouselLite image/page - javascript

I've looked through the other questions about this and not found a suitable answer.
What I need is very simple: The index of the currently shown item.
Here's my little chunk of config
$('.carousel').jCarouselLite(
{
btnNext: "#right-navigation",
btnPrev: "#left-navigation",
visible: 1,
afterEnd: function(a)
{
// Code that requires the index
}
});
Note: the a is an object
Thanks!

The elements representing the items
that are visible after the animation
ends are passed in as argument.
so you should be able to do something like
afterEnd: function(a){
var index = $(a[0]).index();
}
to get the index of the first element

Related

Return value for function is not working correctly. How to set up correct return value for function checkIfExist()?

I am writing a script for Premiere pro where I can add markers in the timeline and export a still for each marker in one go. However, when I write a function to check if the still has been previously created, the functions tells me it finds the previously created still, but then still creates a new one.
So basically: Function returns true, but still executes the else{}
//checks if the frame that is about to be exported already exists
if(checkIfExist(app.project.rootItem, outputFile)){
alert("frame already exists");
}else{
//This is where the actual still gets created and imported
activeSequence.exportFramePNG(time, outputFileName);
//here the previously created item gets moved to the appropriate bin (This is working great ATM)
moveToBin(outputFile);
}
}
}
//This function is meant to check if an item exists in the project bin. It does this by looping though all the items in the array from the start.
function checkIfExist(currentItem, name){
for(var i = 0; i<currentItem.children.numItems; i++){
currentChild = currentItem.children[i];
if(currentChild.name.toUpperCase() === name.toUpperCase()){
alert("Found: " + currentChild.name);
return true;
}if(currentChild.type == ProjectItemType.BIN){
checkIfExist(currentChild, name);
}
}
return false;
}
I think it happens because of the recursion you do:
if(currentChild.type == ProjectItemType.BIN){
checkIfExist(currentChild, name);
}
If this one gets kicked off before you can return true, you will start to run the function for a second time.
Now the first run can return a true, while the second (or even 3th, or 4th, etc) can return false and thus creating a new one, while also finding it.
Also if possible try to use arr.find or arr.findIndex and check if the value is -1 (or not found). This will make your code shorter, cleaner and less open for errors :)
But this will not work for nested arrays. Then you need to make an other function to first make a flat copy that includes all nested array before you do the arr.find or arr.findIndex. Still think that is the better solution.
You can use this to make nested array into a flat one:
let arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flattenDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

I'm trying to use jquery to create a div containing columns but I can't get my array to format correctly

I have an array that contains dates. and for some reason I can't get it to show on my screen I've been debugging for a few days now and I've tracked it down to a single line, but the line has worked before and I can't figure out what the issue might be.
The array looks like this:
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"...];
It's passed as an argument from another function, but that's how it's showing in console.log().
I might be going about this the wrong way, maybe even a lot further around then I need to but this is what I've come up with:
1. function setTHead(selectItems) {
2 var formatString;
3. for (var x = 0; x < 12; x++) {
4. formatString = selectItems[x].replace(/[^0-9/-]/g, "").toString();
5. console.log(selectItems);
6. $('#datTab').append("<div id='col" + x + "' class='column'>'" + formatString + "'</div>");
7. }
8. }
the array up top is what's showing from the console.log 5 lines down.
the sixth line is what is seeming to give me issues. Nothing is put on the page at all.
I'm getting a console error saying:
jQuery.Deferred exception: selectItems is undefined setTHead#http://localhost/mySite/script.js:136:9
startUp2#http://localhost/mySite/script.js:146:5
#http://localhost/mySite/table.php:19:9
mightThrow#http://localhost/mySite/lib/jquery.js:3586:52
resolve/</process<#http://localhost/mySite/lib/jquery.js:3654:49
setTimeout handler*resolve/<#http://localhost/mySite/lib/jquery.js:3692:37
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
fire#http://localhost/mySite/lib/jquery.js:3458:21
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
ready#http://localhost/mySite/lib/jquery.js:3923:13
completed#http://localhost/mySite/lib/jquery.js:3933:9
EventListener.handleEvent*#http://localhost/mySite/lib/jquery.js:3949:9
#http://localhost/mySite/lib/jquery.js:39:9
#http://localhost/mySite/lib/jquery.js:17:3
undefined
followed by:
TypeError: selectItems is undefined
and thats pointing to line 6.
if anyone has any advice I would be very much appreciative. Thank you in advance.
EDIT: A little more code:
function startTblView(defSel) {
if (defSel === true) {
setCookie('defSel', true, 7);
} else{
setCookie('defSel', false, 7);
}
saveSelected();
window.open('table.php', '_self');
defSel = getCookie('defSel');
if (defSel) {
selectItems = getDefDates();
}else {
selectItems = reGetSelected();
}
setTHead(selectItems);
}
defSel, is a boolean passed from my last page stating whether I'm doing a default view or a custom view, the custom view is passed from saveSelected();
saveSelected is a function for just saving the selected global value as a cookie so I can pull it out on the next page.
getDefDates pulls the default values for the array
reGetSelected, gets the selected array from the cookie.
I apologize for wonky naming conventions. I'm the only one working on this site and I'm just making sure the names don't overlap.
You can do this :
HTML code
<div id="datTab"></div>
JS code
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"];
function setTHead(selectItems) {
var formatString;
$.each( selectItems, function( index, value ){
formatString = value.replace(/[^0-9/-]/g, "").toString();
$('#datTab').append("<div id='col" + index + "' class='column'>'" + value + "'</div>");
});
};
You can use $.each, its better than 'for' with javascript.
The .each() method is designed to make DOM looping constructs concise
and less error-prone. When called it iterates over the DOM elements
that are part of the jQuery object. Each time the callback runs, it is
passed the current loop iteration, beginning from 0. More importantly,
the callback is fired in the context of the current DOM element, so
the keyword this refers to the element.
I did a JsFiddle
Here.

JavaScript variable remains undefined

I am struggling with my webpage. The JavaScript isn't doing what it should because a variable[] isn't being populated! Please consider my code:
var datasets = { "DataItem1": {
label: "Idle Count",
dataSeries: [[13, 75.72],[13, 1],[13, 0.17],[13, 55.72],[13, 90.72],[13, 91.06]],
Threshold_0: [[134, 1],[133, 1]],
Threshold_2: [[133, 1],[131, 1]]
}
};
var data = [];
var failedData = [];
data.push(datasets['DataItem1']['dataSeries']);
failedData.push(datasets['DataItem1']['Threshold_0']['Threshold_2']);
});
The issue is with
failedData.push(datasets['DataItem1']['Threshold_0']['Threshold_2']);
Using firebug's watch window, I can see that failedData is undefined when I add a break at this point. So, I hover the mouse over the array items on this line, and Threshold_0 has data, but Threshold_2 does not (Threshold_2 is undefined).
In the watch window, I can see that datasets[] has created all the objects as expected.
I can't see why and I'm very stuck.
Here you are trying to access the property Threshold_2 through Threshold_0, you should get it through DataItem1
failedData.push(datasets['DataItem1']['Threshold_0']['Threshold_2']);
Becomes
failedData.push(datasets['DataItem1']['Threshold_2']);
The following properties do have a value:
datasets['DataItem1']['Threshold_0'][0] == [134, 1]
datasets['DataItem1']['Threshold_0'][1] == [133, 1]
I'm not sure what you actually want to do. Maybe this is what you intend to do?
failedData.push(datasets['DataItem1']['Threshold_0']);
failedData.push(datasets['DataItem1']['Threshold_2']);
Otherwise, please describe what value(s) you want to end up in failedData.
You have a typo at the end. Remove the last });

removing element from mootools sortable

I'm trying to remove an item from a mootools sortable list, then serialize and save the new list.
I'd like to use a little bit of eye-candy rather than a straight destroy() on the element. I've built a fiddle here: http://jsfiddle.net/kBAqJ/4/
Note the order1 and order2 vars. This holds the serialized element before and after removing the item. If you use the destroy method to get rid of the element after removing it from the sortable, you get the right value for order2, eg. 4.
If you use nix(true) instead of destroy, you get 5 as the value of order1 and order2, even though the docs say that nix(true) calls destroy after dissolve.
Is this a bug in Mootools, or am I missing something? Is there a different way to add a dissolve effect while still using destroy that will get the right result?
window.addEvent('domready', function(){
var mySort = new Sortables('#example2 UL', {
clone: true,
revert: true,
opacity: 0.7
});
console.log (mySort.elements.length);
var order1 = mySort.serialize(0);
console.dir(order1);
mySort.removeItems($('item1')).destroy(); // this results in the correct value in the order2 var below
//mySort.removeItems($('item1')).nix({duration: 1000}, true); // this results in the wrong value for order2
console.log (mySort.elements.length);
var order2 = mySort.serialize(0);
console.dir(order2);
});
i don't think you'll find any effect or way which will destroy the element and still show it on the page ;) So it is not a moo tools bug
The serialize function is using the children of the list (ie. the <li> blocks) to make the array.
I would say the easiest way would be to get rid of their reference in the serialized array:
window.addEvent('domready', function(){
var mySort = new Sortables('#example2 UL', {
clone: true,
revert: true,
opacity: 0.7
});
console.log (mySort.elements.length);
var order1 = mySort.serialize(0);
console.dir(order1);
//mySort.removeItems($('item1')).destroy(); // this results in the correct value in the order2 var below
mySort.removeItems($('item1')).nix({duration: 1000}, true); // this results in the wrong value for order2
console.log (mySort.elements.length);
var order2 = mySort.serialize(0).erase("item1"); // we have to erase the item because he may still be in the list of children at this timeā€¦
console.dir(order2);
});
Cheers

JQuery: How to cache DOM?

I used Firefug to profile my web application and found that the following function is called, and needs to be called, literally hundreds of times per user visit. So I want to optimize it since Firebug says it uses the most resources/times.
function highlightChildDiv(parentDiv) {
/* find the closest (hlisting) home listing to the middle of the scrollwindow & highlight */
var scrollElemPos = parentDiv.offset();
var highlightDiv = $(document.elementFromPoint(
scrollElemPos.left + parentDiv.width() / 2,
scrollElemPos.top + parentDiv.height() / 2)
).closest('#parentDiv div.childClass');
if (highlightDiv.hasClass("HighlightRow")) {
return; // if the div is already highlighted, return
} else {
$('#parentDiv div.childClass').removeClass("HighlightRow");
highlightDiv.addClass('HighlightRow');
}
}
Seems to me that one of the most un-optimized statements is .closest('#parentDiv div.childClass');, but I'm sure there is other things to improve.
Question: Does anyone have any JQuery performance tips on how I can optimize the code above given that this function is run literally hundreds of times per user visit.
First thought, eliminate the dead statement in the if clause.
if (!highlightDiv.hasClass("HighlightRow")) {
$('#parentDiv div.childClass').removeClass("HighlightRow");
highlightDiv.addClass('HighlightRow');
}
In the selector #parentDiv div.childClass, can you guarantee that div will be a direct descendent of #parentDiv? In which case:
.closest('#parentDiv>div.childClass');
and
$('#parentDiv>div.childClass')
You already have parentDiv. I'm guessing this is a DOM object, so you may be able to do the following:
$(parentDiv).children("div.childClass")
Just hide the DIV that is currently highlighted:
$('#parentDiv div.HighlightRow').removeClass("HighlightRow");
My guess is this is the most unoptimized line:
$('#parentDiv div.childClass').removeClass("HighlightRow");
You should profile it to make sure (create a date object outside the call and output the getTime() value before and after each call).
Here you are asking jQuery to iterate over all DOM elements that match that selector and remove the class. If there are 1000 rows, jQuery will need to interogate each one to see if it needs to remove a class. Ugh. Here it is with that lookup removed:
// namespace scoped cache
var Hash_$_Cache = {
$parentDiv : $('#parentDiv'),
$tgt_row : $([]) // empty jq object to start
};
// find the closest (hlisting) home listing to the middle of
// the scrollwindow and highlight
//
var highlightChildDiv = function (parentDiv){
var
scrollElemPos = parentDiv.offset(),
$tgt_row
;
$tgt_row = $(document.elementFromPoint(
scrollElemPos.left + parentDiv.width() / 2,
scrollElemPos.top + parentDiv.height() / 2)
).closest('#parentDiv div.childClass')
;
// bail if row is already highlighted
if ($tgt_row.hasClass('HighlightRow')){ return; }
Hash_$_Cache.$tgt_row.removeClass('HighlightRow');
$tgt_row.addClass('HighlightRow');
// save highlighted row for later
Hash_$_Cache.$tgt_row = $tgt_row; // store new row in cache
};
Hope that helps!
I prefer to use the following methodology:
https://gist.github.com/3841424#file-domcache-js
Or, you may replace the DOM object with a method in this implementation:
var myNS = {
myEventHandler: function(event){
this.DOM.$el.doSomething();
},
cacheDOM: function(){
return {
$el: $("#matrix")
};
},
initialize: function(){
this.DOM = this.cacheDOM();
}
};

Categories

Resources