Magnific popup Dynamic content - javascript

I seem to be having an issue where using Magnific and then telling it to programmatically go to the provided index breaks, but only when moving to the zeroth element then back.
I've created a codepen here - codepen
This is the code that appears to be the problem especially with the goTo() method.
if (this.items[i].slug === elSlug)
{
this.goTo(i);
}
else
{
// should log every other index other than the one we're looking for
console.log(i);
}
I also noticed that magnific seems to convert the array/objects provided into an items object with more properties and the provided under a data object.
Has anyone had this kind of issue or know of a way around this?
[edit]
It seems to be something to do with the fact that because of how magnific converts the data (after) opening the modal, it needs to be accessed differently, I've tried changing some conditionals but still no joy =/

Your elSlug variable and the slug property are not consistent. For Example, for Sea Salt & Vinegar, elSlug is set to sea-salt-vinegar but its comparing it against sea-salt-&-vinegar, so its not matching properly.

Fixed my problem, with a little help from a friend!
Turns out magnific changes the items[] array when you initialise the modal.
So we don't just have an array of pure data objects we instead have an object with extra data pushed into it as well as Magnfic placing our supplied data under a data object.
This check got me where I needed to go, hope it helps someone else in the future!
for (i ; i < len ; i++) {
if (this.items[i].slug === elSlug || (this.items[i].data && this.items[i].data.slug === elSlug))
{
this.goTo(i);
break;
} else{
// some kind of problem, do other stuff
}
}

Related

Javascript: Array not shifting, multiple setTimeout functions (JSON)

I'm really stuck on this javascript question!
So I'm making a web page that will be completely animated (so it can be used for display for example in a television). That animation will be configurable by the user (stored in a database).
Right now, I've already made the code to store the configuration and to get the configuration (I do an AJAX call and save the configuration in an array of json objects) and everything is as it should be.
The problem is in the animation in which I go through the array and use setTimeout function to create animations. To iterate through the array I rotate it
(I use array.push(array.shift()) according to the answer here).
The first time the intervalmaster function is used, everything goes according to plan, but when the function is called again I need to rotate the array once more (because of the last animation) and the array just doesn't rotate!
Bellow I've left a portion of the code that I'm using that reproduces the problem I'm getting. I've also added the array jsonanima with some possible values (In reality the array is probably much bigger and with higher values).
I really don't understand what is happening, I've also considered that this could be a problem of the multiple setTimeout functions because I've read somewhere (couldn't find the link, sorry!) that is not really advised to use multiple setTimeout.
If that's the case is there any other way to do this?
Thank you in advance!
EDIT: Thanks to the comment from mplungjan I've realized that if change the console.log(jsonanimate) to console.log(JSON.stringfy(jsonanima)) it outputs the correct values (the json array rotated). This got me even more confused! Why do I need to JSON.stringfy to get the array in the correct order?!
Anyway, can't test this with the full code now as I'm not in the office, tomorrow I'll give more feedback. Thank you mplungjan.
EDIT2: Finally solved my problem! So the thing was the call to the function recursivegroup (recursivegroup(0);), this call was made before I rotated the array, so when restarting the animation the array would still have the incorrect values and every sub-sequential value was wrong.
A special thanks to mplungjan and trincot for the comments that helped me debug this problem.
Bellow I leave the code corrected so anybody with the same problem can check it out.
jsonanima=[{"VD":5,"A":10,"diff":0.25},{"L":7,"IE":8,"diff":0.25}];
function intervalmaster(flag){
function recursivegroup(index)
{
if(index==0)
{
//animateeach(jsonanima,0);
}
setTimeout(function(){
//HERE IT WORKS
jsonanima.push(jsonanima.shift());
console.log(JSON.stringify(jsonanima));
//animateeach(jsonanima,0);
//removed the if statement, since it was irrelevant as mplungjan noted
recursivegroup(index+1);
},(jsonanima[0]['diff'])*60*1000);
}
//Changed this
//recursivegroup(0);
var mastertime=0;
for(var key in jsonanima)
{
mastertime+=(jsonanima[key]['diff']);
}
console.log(mastertime,flag);
console.log(JSON.stringify(jsonanima));
if(flag==true)
{
jsonanima.push(jsonanima.shift());
console.log(JSON.stringify(jsonanima));
}
//changed to here
recursivegroup(0);
masterinterval=setTimeout(function(){intervalmaster(true)},mastertime*60*1000);
}
intervalmaster(false);

"in" operator showing functions in javascript

in my code I was always doing
for(i in vector)...
and it always worked, but the problem is that it somehow changed and now my for shows all the values but also the properties, like "remove" that is a function, and it is breaking my whole code.
I don't know why it suddenly changed, because I didn't do anything and I'm getting crazy with this already.
Do you guys know what is happening with my application?
Another thing is that the code only get this problem on my computer.
If I clone my repository again and try it works for while but then starts the problem again.
Thank you.
The in operator has always had this behaviour. Just check that the property exists directly on the object instead of on the prototype:
for (var i in vector) {
if (vector.hasOwnProperty(i)) {
// Property exists on object
}
}
That should solve your issues.
Tom

How to _prevent_ divs from appearing in random order

Okay, so I'm learning front-end dev with javascript/jquery/bootstrap through FreeCodeCamp. This is not a core part of the project, but I don't understand it and it's distracting me too much. In this code pen here:
http://codepen.io/JDenman6/pen/zqeGwp/ --
I have an array of Twitch.tv usernames that I check through an API and build divs to display them based on the JSON object comes back from the API call.
The weird thing is that every time I refresh the page, I get the divs in a different (apparently random) order. I'm guessing that the API calls are going out asynchronously and the divs are appearing in the order that the API calls finish.
When I Googled for other people having problems with divs in random order I found many solutions for causing random display order, but nothing on preventing it. So then I went looking for a solution to sorting divs and found this post, Ordering DIVs based on class name using Javascript/Jquery, which led me to this bit of code:
$(function(){
var elem = $('#twitcherList').find('div').sort(sortMe);
$('#twitcherList').append(elem);
});
function sortMe(a, b) {
return a.className < b.className;
}
Only I haven't been able to get it to work. I forked off my original codepen to do some poking around here: http://codepen.io/JDenman6/pen/MeYOJP.
The list of divs in the twitcherList in the html tab is from inspecting the twitcherList after rendering the original code. I thought it might be easier to sort them if they're hard coded, rather than coming in from the API call. I also added a little test div and inserted some code into the sort function to 1) check that it was running and 2) double check that a.classname and b.classname were returning what I thought they were, which they are.
I feel like I'm missing something massive, fundamental, and possibly quite obvious. Any thoughts?
You need to return -1, 0 or 1 based on the condition for proper sorting.
function sortMe(a, b) {
return a.className.localeCompare(b.className);
}
For better browser support use,
function sortMe(a, b) {
return a.className < b.className ? 1 : -1;
}

How to get unique id from localStorage for delete button

I have been trying for getting an id from localStorage but unable to achieve it.
My localStorage inside events contains such as below.
[{"id":"ef5","title":"wan","start":"2016-05-12","end":"2016-05-13"},{"id":"ef6","title":"wana","start":"2016-05-21","end":"2016-05-22"},{"id":"ef7","title":"haha","start":"2016-05-25","end":"2016-05-26"},{"id":"ef8","title":"asdas","start":"2016-05-20","end":"2016-05-21"},{"id":"ef9","title":"sdas","start":"2016-05-19","end":"2016-05-20"}]
Now i will provide 2 coding with different method that i have tried so far. For information, i look through into this topic: localstorage: Get specific localstorage value of which contains many items
but none works for me.
I did tried coding as below:
1st method:
$("#deleteEventYes").click(function(){
var indexDel = localStorage.getItem("events");
var deleteId = calEvent.id;
var result = localStorage.getItem("events");
function getItemHrefById(json, itemId){
return $(json).filter(function(){return this.id == itemId;})[0].href;
}
var href = getItemHrefById(result, deleteId);
alert(href); });
Above code show some kind of array method (i think) where i'm using indexDel to get item from localStorage (events) while deleteId i took from calEvent.id which is the id for the event that has been clicked for to be deleted. Other than that, i think you guys know what it is. However for this method, i use result variable instead of indexDel. Thus don't mind if i getItem from localStorage 2 times
2nd method:
for (var i = 0 ; i < indexDel.length ; i += 1) {
if(deleteId == indexDel[i].id) {
return indexDel[i];
console.log(deleteId);
console.log(indexDel[i]);
}
}
return null;
Above code is using custom loop i think. The declaration of variable for indexDel is still the same with first method. I try to use the refactoring method but it seems its hard for me to understand how is it to be done. Is it because my variable placement is wrong? or is it because it is not suitable for my case?
NOTE: I want to delete an event inside eventClick function, and so far i did retrieve the id and remove the event from the calendar based on id. However my only problem now is to match the deleted event id with the id inside my localStorage and remove the item. So far getting an id from the is quite complicated for me.
UPDATED
I already done something like this but still don't work. Anyone can tell me what went wrong here? It is not giving me any error but it just do nothing. Not even delete.
https://jsfiddle.net/v35a2o07/3/
Never mind. I think i figure it out :)
It is because i forgot to setItem & stringify it after using splice.
Here i can assume splice is the same as add/remove such wrote at w3school
http://www.w3schools.com/jsref/jsref_splice.asp
"The splice() method adds/removes items to/from an array, and returns the removed item(s)."
My final code is on this fiddle given: https://jsfiddle.net/v35a2o07/4/
So the concept is:
1) First step is declare one variable that parse your localStorage key such asvar items = JSON.parse(localStorage["events"]); so that you can use it for the loop
2) Use for loop to determine the length of localStorage based on localStorage key that we parse on No. 1
3) Use if statement to check the comparison between localStorage data with our desire data such as if(items[i].id == deleteId){
4) This is OPTIONAL but important. To enable you to check the comparison is right, create one alert or console.log() and stringify it because if you don't, you will only see [object,object]. The coding such as alert(JSON.stringify(items[i])+"<<<>>>"+deleteId); Make some else statement too if you want to be sure.
5) When all the conditions are correct, then you are ready to do some action to it. For my case, i just use splice() to delete it. It is also can be used to add item. I am not sure how is it done but try to search for it to get more info.
6) After splicing it, it is safely to break and get out from the loop.
7) This is important otherwise, it will not work. Don't forget to set it back to localStorage and stringify it such as localStorage.setItem('events', JSON.stringify(items));
That's it.
I wish this would help anyone that needs it. If i have make wrong statement or wrong concept, please make correction and clarify it for anyone.
Cheers.

javascript / omniture - how to clear all properties of an object (s object)

I'm using omniture and tracking various properties to the "s" variable for tracking. The example code I'm following calls a function called s.clearVars() after each tracking event. But I get an error saying that clearVars is not a valid function. Does anyone know what I'm supposed to call to clear the tracking object? Or how to clear all properties from a javascript object.
Don't clear the entire s object, it contains a lot of functions that are listening to dom events and if you clear those, you'll lose a lot of functionality. I'm guessing you just want to clear all of the custom variables that you are populating on the page (props, evars, events, products, etc). The s.clearVars function is a "plugin" that Omniture consulting wrote that clears all of these values for you. You could contact your Omniture Account manager and ask him for the code, he may or may not give it to you, depending on whether he wants to sell you some consulting hours or if he knows what you are talking about, or you could do this yourself with a couple of simple loops:
function ClearVars(){
for (var i=0; i < 75; i++) {
s['prop'+i]='';
s['eVar'+i]='';
if(i<=5)
s['hier'+i]='';
}
svarArr = ['pageName','channel','products','events','campaign','purchaseID','state','zip','server','linkName'];
for (var i=0; i < svarArr.length ; i++) {
s[svarArr[i]]='';
}
}
Please note I haven't tested the code. Just shot it from the hip.
Small Correction to Vector Frogs (amazing) code.
The second for loop need to have i=0 to clear out the pageName variable.
Great Script V_FRog!
this will reset the entire object as per your original request:
s=s_gi(s_account);
I think the best answer for how to clear the properties off of a JS object is to just create a new object all together.
Check out this post: How to quickly clear a Javascript Object?
s = {};

Categories

Resources