Videojs removeChild method not working - javascript

I'm writing a new plugin for videojs. I have an issue with the if statement:
if (getCTime == 5 && c == true) {
this.removeChild(createDiv);
}
It can not remove div element after 5 seconds. What should I do?
Code:
(function() {
'use strict';
//Create Component
videojs.containerDiv = videojs.Component.extend({
init: function(player, options) {
videojs.Component.call(this, player, options);
}
});
// get current time and create new element
videojs.containerDiv.prototype.timeUpdate = function(player, options) {
var c = false;
this.player_.on('timeupdate', function() {
var getCTime = Math.floor(this.cache_.currentTime);
var createDiv = new videojs.containerDiv(this, options);
// In 2 seconds are show ads
if (getCTime == 2 && c == false) {
// Create new div for ads
this.addChild(createDiv);
//Close ads
this.one(createDiv.newDivClose_,'click', function() {
this.removeChild(createDiv);
});
c = true;
}
if (getCTime == 5 && c == true) {
this.removeChild(createDiv);
}
});
}
videojs.containerDiv.prototype.createEl = function() {
var newDiv = videojs.createEl('div', {
className: 'vjs-new-div'
});
var newDivInside = videojs.createEl('div', {
className: 'vjs-new-div-inside'
});
var newDivClose = videojs.createEl('div', {
className: 'vjs-btn-close',
innerHTML: 'x'
});
this.newDivClose_ = newDivClose;
newDiv.appendChild(this.newDivClose_);
this.contentEl_ = newDivInside;
this.contentEl_.innerHTML = this.innerHTML();
newDiv.appendChild(this.contentEl_);
return newDiv;
};
videojs.containerDiv.prototype.innerHTML = function() {
this.textAds = "Hello World";
return this.textAds;
}
var pluginFn = function(options) {
var myComponent = new videojs.containerDiv(this, options);
myComponent.timeUpdate(this, options);
};
videojs.plugin( 'myPlugin', pluginFn );
})();

Related

i have a tempermonkey script which read data from csv file .....i want to change it based on fields on webpage

The script loads data from a CSV file. Page sometimes has five fields,
sometimes four. The script needs to adjust based on the number of fields.
forexample I need to modify this tempermonkey script
enter 4 pieces of data if there are 4 fields or enter 5 pieces of data if
there are 5 fields on the web page.
$(window).ready(function($) {
var file = GM_getResourceText('csvFile');
var csv = $.csv.toArrays(file);
var row = 0;
//var interval = setInterval(fillFormInterval, 3000);
var scope = angular.element($('body')).scope();
// scope.$on('$includeContentLoaded', function(){
// fillForm(csv[row]);
//setTimeout(fillForm(csv[row]));
//});
var interval = setInterval(fillFormInterval, 1000);
functionfillFormInterval() {
if($('#applicant-preferredCommunicationMethod').length) {
clearInterval(interval);
setTimeout(function() {
fillForm(csv[row]);
},3000);
}
}
functionfillForm(tempRow) {
var scope = angular.element($('#applicant-firstName')).scope();
if(!scope.applicant || !scope.applicant.phone1) {
return;
}
var row = new Array(5).fill(undefined);
row[1] = "NMN";
tempRow.forEach(function(data,i) {
if(data != '') {
row[i] = data;
}
});
scope.$apply(function() {
scope.applicant.firstName = row[0];
scope.applicant.middleName = row[1];
scope.applicant.lastName = row[2];
scope.applicant.dateOfBirth = row[3];
scope.applicant.dateOfBirth2 = row[3];
scope.applicant.phone1.number = row[4];
scope.applicant.preferredCommunicationMethod = "PHONE1";
scope.inherited.next();
});
//scope.applicant.countryOfBirth = "CD";
}
var interval_2 = setInterval(fillFormInterval_2, 1000);
function fillFormInterval_2() {
if($('#applicant-countryOfBirth').length) {
clearInterval(interval_2);
setTimeout(function() {
fillForm_2(csv[row]);
},3000);
}
}
functiondropDownVal(id, text) {
var value = null;
$(id).each(function() {
if(this.text.toLowerCase() == text) {
value = this.value;
value = value.split(':');
if(value.length> 1) {
value = value[1];
}else {
value = value[0];
}
}
});
return value;
}
function fillForm_2(data) {
var scope = angular.element($('#applicant-
countryOfBirth')).scope();
var country = '';
country = dropDownVal('#applicant-countryOfBirth option',
data[5].toLowerCase());
//scope.applicant.countryOfBirth = country;
var state = null;
scope.$apply(function() {
scope.applicant.countryOfBirth = country;
scope.updateStateProvince(scope.applicant.countryOfBirth);
setTimeout(function() {
if(country == "US" || country == "CD" || country == "MM") {
state = dropDownVal('#applicant-stateProvinceOfBirth
option', data[6].toLowerCase());
}
var citizen = dropDownVal('#applicant-countryOfCitizenship
option', data[7].toLowerCase());
console.log(country + " " + state + " " + citizen);
scope.applicant.countryOfCitizenship = citizen;
scope.applicant.stateProvinceOfBirth = state;
scope.$apply();
scope.inherited.next();
});
});
}
var interval_3 = setInterval(fillFormInterval_3, 1000);
function fillFormInterval_3() {
if($('.personal-questions').length) {
clearInterval(interval_3);
setTimeout(function() {
fillForm_3(csv[row]);
},3000);
}
}
function fillForm_3(data) {
e.applicant.hasMaidenPreviousName = false;
scope.applicant.hasAliasName = false;
scope.applicant.hasSameMailingResidentialAddress = true;
scope.applicant.doYouHaveAuthCode = false;
scope.applicant.viewEcNearYou = false;
scope.inherited.next();
});
}
var interval_4 = setInterval(fillFormInterval_4, 1000);
function fillFormInterval_4() {
if($('#ue-btn-US').length) {
clearInterval(interval_4);
setTimeout(function() {
fillForm_4(csv[row]);
},3000);
}
}
function fillForm_4(data) {
var scope = angular.element($('#applicant-eyeColor')).scope();
scope.$apply(function() {
scope.heightFt = parseInt(data[8].substr(0,1));
scope.heightIn = parseInt(data[8].substr(1,3));
scope.weightLb = parseInt(data[9]);
scope.applicant.hairColor = dropDownVal('#applicant-hairColor
option',
data[10].toLowerCase());
scope.applicant.eyeColor = dropDownVal('#applicant-eyeColor
option',
data[11].toLowerCase());
scope.applicant.gender = dropDownVal('#applicant-gender
option',
data[12].toLowerCase());
if(data[13].toLowerCase() == 'mixed race') {
data[13] = 'Unknown';
}else if(data[13].toLowerCase() == 'white' ||
data[13].toLowerCase() ==
'hispanic') {
data[13] = 'Caucasian/Latino';
}
scope.applicant.race = dropDownVal('#applicant-race option',
data[13].toLowerCase());
scope.inherited.next();
});
}
var interval_5 = setInterval(fillFormInterval_5, 1000);
function fillFormInterval_5() {
if($('#applicant-mailingAddress-country').length) {
clearInterval(interval_5);
setTimeout(function() {
fillForm_5(csv[row]);
},3000);
}
}
function fillForm_5(data) {
var scope = angular.element($('#applicant-mailingAddress-
country')).scope();
scope.$apply(function() {
scope.applicant.mailingAddress = {};
scope.applicant.mailingAddress.country = "US";
scope.updateStates('mailingAddress');
scope.applicant.mailingAddress.addressLine1 = data[14];
scope.applicant.mailingAddress.addressLine2 = data[15];
scope.applicant.mailingAddress.city = data[16];
setTimeout(function() {
scope.$apply(function() {
scope.applicant.mailingAddress.state = dropDownVal('#applicant-
mailingAddress-state option', data[17].toLowerCase());
scope.applicant.mailingAddress.postalCode = data[18];
scope.inherited.next();
});
});
//scope.inherited.next();
});
}
var interval_6 = setInterval(fillFormInterval_6, 1000);
function fillFormInterval_6() {
if($('#designatedRecipient-name').length) {
clearInterval(interval_6);
setTimeout(function() {
fillForm_6(csv[row]);
},3000);
}
}
function fillForm_6(data) {
var scope = angular.element($('#designatedRecipient-
name')).scope();
scope.$apply(function() {
scope.applicant.designatedRecipientName = "BIOVERIFY INC";
scope.applicant.designatedRecipientAddress = {};
scope.applicant.designatedRecipientAddress.country = "US";
scope.applicant.designatedRecipientAddress.addressLine1 = "2535
Manana
Dr.";
scope.applicant.designatedRecipientAddress.city = "Dallas";
setTimeout(function() {
scope.$apply(function() {
scope.applicant.designatedRecipientAddress.state =
dropDownVal('#applicant-designatedRecipientAddress-state
option', 'texas');
scope.applicant.designatedRecipientAddress.postalCode =
"75220";
scope.inherited.next();
});
});
scope.updateStates();
});
}
var interval_7 = setInterval(fillFormInterval_7, 1000);
function fillFormInterval_7() {
if($('#payment-nameOnCard').length) {
clearInterval(interval_7);
setTimeout(function() {
fillForm_7(csv[row]);
},3000);
}
}
function fillForm_7(data) {
var scope = angular.element($('#payment-nameOnCard')).scope();
scope.$apply(function() {
scope.applicant.payment.nameOnCard = "Brendan J Berrells";
scope.applicant.payment.cardNumber = "4246315197117185";
scope.applicant.payment.expiration = {};
scope.applicant.payment.expiration.month = 11;
scope.applicant.payment.expiration.year = "19";
scope.applicant.payment.csc = "255";
});
}
});

when click on button the time is count and show totall time

hi gyzz i am new in jquery , when i click add button the running time is count suddenly when i click add button and its count , i click 3 times and its count different time and when i click totall button then show total time that i click 3 times add 3 different time , how this is possible... i use simple stopwatch plugin..
my code is
(function( $ ){
//my code
$('#demo1').stopwatch().stopwatch('start');
//count time indually
$(".add_time").click(function(e) {
e.preventDefault();
var time_record = $('.example').find('#timer').text();
var time_record++;
console.log(time_record);
});
//get totall time
$(".totall_time").click(function(e) {
e.preventDefault();
});
//stopwatch plugin
function incrementer(ct, increment) {
return function() { ct+=increment; return ct; };
}
function pad2(number) {
return (number < 10 ? '0' : '') + number;
}
function defaultFormatMilliseconds(millis) {
var x, seconds, minutes, hours;
x = millis / 1000;
seconds = Math.floor(x % 60);
x /= 60;
minutes = Math.floor(x % 60);
x /= 60;
// hours = Math.floor(x % 24);
// x /= 24;
// days = Math.floor(x);
return [pad2(minutes), pad2(seconds)].join(':');
}
//NOTE: This is a the 'lazy func def' pattern described at http://michaux.ca/articles/lazy-function-definition-pattern
function formatMilliseconds(millis, data) {
// Use jintervals if available, else default formatter
var formatter;
if (typeof jintervals == 'function') {
formatter = function(millis, data){return jintervals(millis/1000, data.format);};
} else {
formatter = defaultFormatMilliseconds;
}
formatMilliseconds = function(millis, data) {
return formatter(millis, data);
};
return formatMilliseconds(millis, data);
}
var methods = {
init: function(options) {
var defaults = {
updateInterval: 1000,
startTime: 0,
format: '{HH}:{MM}:{SS}',
formatter: formatMilliseconds
};
// if (options) { $.extend(settings, options); }
return this.each(function() {
var $this = $(this),
data = $this.data('stopwatch');
// If the plugin hasn't been initialized yet
if (!data) {
// Setup the stopwatch data
var settings = $.extend({}, defaults, options);
data = settings;
data.active = false;
data.target = $this;
data.elapsed = settings.startTime;
// create counter
data.incrementer = incrementer(data.startTime, data.updateInterval);
data.tick_function = function() {
var millis = data.incrementer();
data.elapsed = millis;
data.target.trigger('tick.stopwatch', [millis]);
data.target.stopwatch('render');
};
$this.data('stopwatch', data);
}
});
},
start: function() {
return this.each(function() {
var $this = $(this),
data = $this.data('stopwatch');
// Mark as active
data.active = true;
data.timerID = setInterval(data.tick_function, data.updateInterval);
$this.data('stopwatch', data);
});
},
stop: function() {
return this.each(function() {
var $this = $(this),
data = $this.data('stopwatch');
clearInterval(data.timerID);
data.active = false;
$this.data('stopwatch', data);
});
},
destroy: function() {
return this.each(function(){
var $this = $(this),
data = $this.data('stopwatch');
$this.stopwatch('stop').unbind('.stopwatch').removeData('stopwatch');
});
},
render: function() {
var $this = $(this),
data = $this.data('stopwatch');
$this.html(data.formatter(data.elapsed, data));
},
getTime: function() {
var $this = $(this),
data = $this.data('stopwatch');
return data.elapsed;
},
toggle: function() {
return this.each(function() {
var $this = $(this);
var data = $this.data('stopwatch');
if (data.active) {
$this.stopwatch('stop');
} else {
$this.stopwatch('start');
}
});
},
reset: function() {
return this.each(function() {
var $this = $(this);
data = $this.data('stopwatch');
data.incrementer = incrementer(data.startTime, data.updateInterval);
data.elapsed = data.startTime;
$this.data('stopwatch', data);
});
}
};
// Define the function
$.fn.stopwatch = function( method ) {
if (methods[method]) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.stopwatch' );
}
};
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="example">
<div class="label">Count up from now</div>
<div id="demo1" class="demo">00:00</div>
</div>
<button class="add_time">add</button>
<button class="totall_time">totall time</button>

JavaScript - Set function to return all items based on 1 or 2 selected tags (NO jQUERY)

I have some JavaScrip that is meant to check if there are any media tags selected or industry tags selected--this is so the portfolio items can be sorted and displayed accordingly in the browser.
What I have almost works 100%, but I can't figure out how to make it so that if only a media tag is selected or if only an industry tag is selected, the portfolio items should still be sorted accordingly. Currently, you have to select a media tag AND an industry tag, but I'd like users to be able to search using just a media tag OR just an industry tag.
Here is what I want to accomplish: If only a media tag is selected, then get all portfolio pieces that are associated with that media tag. If only an industry tag is selected, get all portfolio items that are associated with that industry tag. If a media tag AND industry tag are selected at the same time, get all portfolio items that are associated with BOTH.
Vanilla JS isn't my strong point so forgive me if this is a dumb question, but this has had me stumped for hours now.
No jQuery answers, please, as this whole page's functionality is built using JavaScript.
Here is the function:
var update = function () {
closeDrawer();
// update ui to reflect tag changes
// get our list of items to display
var itemsToDisplay = [];
var currentMediaTag = controlsContainer.querySelector('.media.selected');
var currentIndustryTag = controlsContainer.querySelector('.industry.selected');
if (currentMediaTag != "" && currentMediaTag != null) {
selectedMediaFilter = currentMediaTag.innerHTML;
}
if (currentIndustryTag != "" && currentIndustryTag != null) {
selectedIndustryFilter = currentIndustryTag.innerHTML;
}
if (selectedMediaFilter == "" && selectedIndustryFilter == "") {
itemsToDisplay = portfolioItems.filter(function (item) {
return item.preferred;
});
} else {
itemsToDisplay = portfolioItems.filter(function (item) {
var mediaTags = item.media_tags,
industryTags = item.industry_tags;
if(industryTags.indexOf(selectedIndustryFilter) < 0){
return false;
}
else if(mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
else{
return true;
}
});
}
renderItems(itemsToDisplay);
}
Not entirely sure it's necessary but just in case, here is the complete JS file that handles the portfolio page:
(function ($) {
document.addEventListener("DOMContentLoaded", function (event) {
// for portfolio interaction
var portfolioGrid = (function () {
var gridSize = undefined,
parentContainer = document.querySelector('.portfolio-item-container');
containers = parentContainer.querySelectorAll('.view'),
drawer = parentContainer.querySelector('.drawer'),
bannerContainer = drawer.querySelector('.banner-container'),
thumbsContainer = drawer.querySelector('.thumbs-container'),
descriptionContainer = drawer.querySelector('.client-description'),
clientNameContainer = drawer.querySelector('.client-name'),
controlsContainer = document.querySelector('.portfolio-controls-container'),
selectedMediaFilter = "", selectedIndustryFilter = "";
var setGridSize = function () {
var windowSize = window.innerWidth,
previousGridSize = gridSize;
if (windowSize > 1800) {
gridSize = 5;
} else if (windowSize > 900) {
gridSize = 4;
} else if (windowSize > 600 && windowSize <= 900) {
gridSize = 3;
} else {
gridSize = 2;
}
if (previousGridSize != gridSize) {
closeDrawer();
}
};
var attachResize = function () {
window.onresize = function () {
setGridSize();
};
};
var getRowClicked = function (boxNumber) {
return Math.ceil(boxNumber / gridSize);
};
var getLeftSibling = function (row) {
var cI = row * gridSize;
return containers[cI >= containers.length ? containers.length - 1 : cI];
};
var openDrawer = function () {
drawer.className = 'drawer';
scrollToBanner();
};
var scrollToBanner = function () {
var mainContainer = document.querySelector('#main-container'),
mainBounding = mainContainer.getBoundingClientRect(),
scrollY = (drawer.offsetTop - mainBounding.bottom) - 10,
currentTop = document.body.getBoundingClientRect().top;
animate(document.body, "scrollTop", "", document.body.scrollTop, scrollY, 200, true);
};
var animate = function (elem, style, unit, from, to, time, prop) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function () {
var step = Math.min(1, (new Date().getTime() - start) / time);
if (prop) {
elem[style] = (from + step * (to - from)) + unit;
} else {
elem.style[style] = (from + step * (to - from)) + unit;
}
if (step == 1) clearInterval(timer);
}, 25);
elem.style[style] = from + unit;
}
var closeDrawer = function () {
drawer.className = 'drawer hidden';
};
var cleanDrawer = function () {
bannerContainer.innerHTML = "";
clientNameContainer.innerHTML = "";
descriptionContainer.innerHTML = "";
thumbsContainer.innerHTML = "";
};
var resetThumbs = function () {
Array.prototype.forEach.call(thumbsContainer.querySelectorAll('.thumb'), function (t) {
t.className = "thumb";
});
};
var handleBannerItem = function (item) {
bannerContainer.innerHTML = "";
if (item.youtube) {
var videoContainer = document.createElement('div'),
iframe = document.createElement('iframe');
videoContainer.className = "videowrapper";
iframe.className = "youtube-video";
iframe.src = "https://youtube.com/embed/" + item.youtube;
videoContainer.appendChild(iframe);
bannerContainer.appendChild(videoContainer);
} else if (item.soundcloud) {
var iframe = document.createElement('iframe');
iframe.src = item.soundcloud;
iframe.className = "soundcloud-embed";
bannerContainer.appendChild(iframe);
} else if (item.banner) {
var bannerImage = document.createElement('img');
bannerImage.src = item.banner;
bannerContainer.appendChild(bannerImage);
}
};
var attachClick = function () {
Array.prototype.forEach.call(containers, function (n, i) {
n.querySelector('a.info').addEventListener('click', function (e) {
e.preventDefault();
});
n.addEventListener('click', function (e) {
var boxNumber = i + 1,
row = getRowClicked(boxNumber);
var containerIndex = row * gridSize;
if (containerIndex >= containers.length) {
// we're inserting drawer at the end
parentContainer.appendChild(drawer);
} else {
// we're inserting drawer in the middle somewhere
var leftSiblingNode = getLeftSibling(row);
leftSiblingNode.parentNode.insertBefore(drawer, leftSiblingNode);
}
// populate
cleanDrawer();
var mediaFilterSelected = document.querySelector('.media-tags .tag-container .selected');
var selectedFilters = "";
if (mediaFilterSelected != "" && mediaFilterSelected != null) {
selectedFilters = mediaFilterSelected.innerHTML;
}
var portfolioItemName = '';
var selectedID = this.getAttribute('data-portfolio-item-id');
var data = portfolioItems.filter(function (item) {
portfolioItemName = item.name;
return item.id === selectedID;
})[0];
clientNameContainer.innerHTML = data.name;
descriptionContainer.innerHTML = data.description;
var childItems = data.child_items;
//We will group the child items by media tag and target the unique instance from each group to get the right main banner
Array.prototype.groupBy = function (prop) {
return this.reduce(function (groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
var byTag = childItems.groupBy('media_tags');
if (childItems.length > 0) {
handleBannerItem(childItems[0]);
var byTagValues = Object.values(byTag);
byTagValues.forEach(function (tagValue) {
for (var t = 0; t < tagValue.length; t++) {
if (tagValue[t].media_tags == selectedFilters) {
handleBannerItem(tagValue[0]);
}
}
});
childItems.forEach(function (item, i) {
var img = document.createElement('img'),
container = document.createElement('div'),
label = document.createElement('p');
container.appendChild(img);
var mediaTags = item.media_tags;
container.className = "thumb";
label.className = "childLabelInactive thumbLbl";
thumbsContainer.appendChild(container);
if (selectedFilters.length > 0 && mediaTags.length > 0) {
for (var x = 0; x < mediaTags.length; x++) {
if (mediaTags[x] == selectedFilters) {
container.className = "thumb active";
label.className = "childLabel thumbLbl";
}
}
}
else {
container.className = i == 0 ? "thumb active" : "thumb";
}
img.src = item.thumb;
if (item.media_tags != 0 && item.media_tags != null) {
childMediaTags = item.media_tags;
childMediaTags.forEach(function (cMTag) {
varLabelTxt = document.createTextNode(cMTag);
container.appendChild(label);
label.appendChild(varLabelTxt);
});
}
img.addEventListener('click', function (e) {
scrollToBanner();
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
});
}
openDrawer();
});
});
};
var preloadImages = function () {
portfolioItems.forEach(function (item) {
var childItems = item.child_items;
childItems.forEach(function (child) {
(new Image()).src = child.banner;
(new Image()).src = child.thumb;
});
});
};
//////////////////////////////////// UPDATE FUNCTION /////////////////////////////////////
var update = function () {
closeDrawer();
// update ui to reflect tag changes
// get our list of items to display
var itemsToDisplay = [];
var currentMediaTag = controlsContainer.querySelector('.media.selected');
var currentIndustryTag = controlsContainer.querySelector('.industry.selected');
if (currentMediaTag != "" && currentMediaTag != null) {
selectedMediaFilter = currentMediaTag.innerHTML;
}
if (currentIndustryTag != "" && currentIndustryTag != null) {
selectedIndustryFilter = currentIndustryTag.innerHTML;
}
if (selectedMediaFilter == "" && selectedIndustryFilter == "") {
itemsToDisplay = portfolioItems.filter(function (item) {
return item.preferred;
});
} else {
itemsToDisplay = portfolioItems.filter(function (item) {
var mediaTags = item.media_tags,
industryTags = item.industry_tags;
if (industryTags.indexOf(selectedIndustryFilter) < 0) {
return false;
}
else if (mediaTags.indexOf(selectedMediaFilter) < 0) {
return false;
}
else {
return true;
}
});
}
renderItems(itemsToDisplay);
}
//////////////////////////////////// RENDERITEMS FUNCTION /////////////////////////////////////
var renderItems = function (items) {
var children = parentContainer.querySelectorAll('.view');
Array.prototype.forEach.call(children, function (child) {
// remove all event listeners then remove child
parentContainer.removeChild(child);
});
items.forEach(function (item) {
var container = document.createElement('div'),
thumb = document.createElement('img'),
mask = document.createElement('div'),
title = document.createElement('h6'),
excerpt = document.createElement('p'),
link = document.createElement('a');
container.className = "view view-tenth";
container.setAttribute('data-portfolio-item-id', item.id);
thumb.src = item.thumb;
mask.className = "mask";
title.innerHTML = item.name;
excerpt.innerHTML = item.excerpt;
link.href = "#";
link.className = "info";
link.innerHTML = "View Work";
container.appendChild(thumb);
container.appendChild(mask);
mask.appendChild(title);
mask.appendChild(excerpt);
mask.appendChild(link);
parentContainer.insertBefore(container, drawer);
});
containers = parentContainer.querySelectorAll('.view');
attachClick();
};
var filterHandler = function (linkNode, tagType) {
var prevSelection = document.querySelector("." + tagType + '.selected');
if (prevSelection != "" && prevSelection != null) {
prevSelection.className = tagType + ' tag';
}
linkNode.className = tagType + ' tag selected';
update();
};
var clearFilters = function (nodeList, filterType) {
Array.prototype.forEach.call(nodeList, function (node) {
node.className = filterType + " tag";
console.log("Clear filters function called");
});
}
var attachFilters = function () {
var mediaFilters = controlsContainer.querySelectorAll('.tag.media'),
industryFilters = controlsContainer.querySelectorAll('.tag.industry'),
filterToggle = controlsContainer.querySelectorAll('.filter-toggle');
// resets
controlsContainer.querySelector('.media-tags .reset')
.addEventListener('click',
function (e) {
e.preventDefault();
selectedMediaFilter = "";
clearFilters(controlsContainer.querySelectorAll('.media-tags a.tag'), "media");
update();
}
);
controlsContainer.querySelector('.industry-tags .reset')
.addEventListener('click',
function (e) {
e.preventDefault();
selectedIndustryFilter = "";
clearFilters(controlsContainer.querySelectorAll('.industry-tags a.tag'), "industry");
update();
}
);
Array.prototype.forEach.call(filterToggle, function (toggle) {
toggle.addEventListener('click', function (e) {
if (controlsContainer.className.indexOf('open') < 0) {
controlsContainer.className += ' open';
} else {
controlsContainer.className = controlsContainer.className.replace('open', '');
}
});
});
//Attaches a click event to each media tag "button"
Array.prototype.forEach.call(mediaFilters, function (filter) {
filter.addEventListener('click', function (e) {
e.preventDefault();
// var selectedMediaFilter = controlsContainer.querySelector('.media.selected');
//console.log("Media tag: " +this.innerHTML); *THIS WORKS*
filterHandler(this, "media");
});
});
Array.prototype.forEach.call(industryFilters, function (filter) {
filter.addEventListener('click', function (e) {
e.preventDefault();
// var selectedIndustryFilter = this.querySelector('.industry.selected');
// console.log("Industry tag: " +this.innerHTML); *THIS WORKS*
filterHandler(this, "industry");
});
});
};
return {
init: function () {
setGridSize();
attachResize();
attachClick();
preloadImages();
// portfolio page
if (controlsContainer) {
attachFilters();
}
}
};
})();
portfolioGrid.init();
});
}());
$ = jQuery.noConflict();
if(industryTags.indexOf(selectedIndustryFilter) < 0){
return false;
}
else if(mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
That part is giving you headaches. Whenever no industry tag or media tag is selected this will exit the function.
Change to:
if(industryTags.indexOf(selectedIndustryFilter) < 0 && mediaTags.indexOf(selectedMediaFilter) < 0){
return false;
}
Now it will test if at least one tag is selected. If so then render items.
I made a change just to experiment with an idea, and this setup works:
if((selectedIndustryFilter !="" && industryTags.indexOf(selectedIndustryFilter) < 0) || (selectedMediaFilter !="" && mediaTags.indexOf(selectedMediaFilter) < 0)){
return false;
}
return true;
Not sure if it's the best solution ever but it seems to work and I'm not going to complain.

detect when 2 calendar values changed

I am making a financial report where user choose 2 dates search_date1 and search_date2, and then a monthly report is generated.
I created first a daily report with only one calendar and when it is changed I apply some AJAX script to it and it works correctly:
var myApp = {};
myApp.search_date = "";
document.getElementById('search_date').onchange = function (e) {
if (this.value != myApp.search_date) {
var d = $("#search_date").val();
$.ajax({
...
});
}
}
Now I can't know how to detect if both calendars are changed to apply AJAX script according to their values.
EDIT
Is it correct to do the following:
var myApp = {};
myApp.search_date1 = "";
myApp.search_date2 = "";
document.getElementById('search_date1').onchange = function (e) {
if (this.value != myApp.search_date1) {
var d1 = $("#search_date1").val();
document.getElementById('search_date2').onchange = function (e) {
if (this.value != myApp.search_date2) {
var d2 = $("#search_date2").val();
$.ajax({
...
})
}
});
}
});
try this:
var temp = {
from: null,
to: null
}
document.getElementById('from').onchange = function(e){
temp.from = e.target.value;
goAjax();
}
document.getElementById('to').onchange = function(e){
temp.to = e.target.value;
goAjax();
}
function goAjax(){
if(temp.from && temp.to && new Date(temp.from) < new Date(temp.to)){
//do ajax call
console.log('valid')
}
}
<input type="date" id='from'/>
<br>
<input type="date" id='to'/>
I would have captured the change event for both elements :
$("#search_date1, #search_date2").on('change',function(){
var d1 = $("#search_date1").val();
var d2 = $("#search_date2").val();
$.ajax({...});
});
What you do in your edit may work, but it would be better (and easier) do something like this
var myApp = {};
myApp.original_search_date1 = $("#search_date1").val();
myApp.original_search_date2 = $("#search_date2").val();
myApp.search_date1 = $("#search_date1").val();
myApp.search_date2 = $("#search_date2").val();
document.getElementById('search_date1').onchange = function (e) {
if ($("#search_date1").val() != myApp.search_date1) {
myApp.search_date1 = $("#search_date1").val();
sendAjax();
}
});
document.getElementById('search_date2').onchange = function (e) {
if ($("#search_date2").val() != myApp.search_date2) {
myApp.search_date2 = $("#search_date2").val();
sendAjax();
}
});
function sendAjax() {
if (myApp.original_search_date1 !== myApp.search_date1 &&
myApp.original_search_date2 !== myApp.search_date2) {
$.ajax({
...
});
}
}
Cant you just set a variable to check if its been changed with true/false then run the script if both variables are true.
Something like,
var searchOneToggled = false,
searchTwoToggled = false;
$('#search_date_one').on('input', function() {
searchOneToggled = true;
runYourFunction();
});
$('#search_date_two').on('input', function() {
searchTwoToggled = true;
runYourFunction();
});
function runYourFunction() {
if(searchOneToggled === true && searchTwoToggled === true) {
alert('hello world');
}
}

Javascript file "FASW transitions" duplicating my header info. How to fix

Ok! I'm working on a wordpress site, and everything this javascript add on is supposed to do, it does...But, when I inspect element via safari develop, I notice that it's loading all of my headers scripts,meta,styles etc. into the body as well as the head. I can't figure out why. Here's what the script looks like:
function ft(params) {
var ol= document.addEventListener?"DOMContentLoaded":"load"; //on load event
var navB = params.navB || "reverse slide"; //backbrowser button effect, default empty
var but = params.but || false; //Allow transitions on input type button
var cBa = params.cBa || function() {};
function aDL(url, t, o) { //Ajax Div Load
if (window.XMLHttpRequest) {
r = new XMLHttpRequest();
} else if (window.ActiveXObject) {
r = new ActiveXObject("Microsoft.XMLHTTP");
}
if (r != undefined) {
r.onreadystatechange = function() {Ol(r, t, o);};
r.open("GET", url, true);
r.send("");
}
}
function Ol(r, t, o) { //On load div
if (r.readyState == 4) {
if (r.status == 200 || r.status == 0) {
t.innerHTML = r.responseText;
o();
} else {
t.innerHTML="Error:\n"+ r.status + "\n" +r.statusText;
}
}
}
function DE() //Div Effect
{
var dochtml = document.body.innerHTML;
document.body.innerHTML = "";
var d1 = document.createElement("div");
d1.id = "d1";
d1.style.zIndex = 2;
d1.style.position = "absolute";
d1.style.width = "100%";
d1.style.height = "100%";
d1.style.left = "0px";
d1.style.top = "0px";
document.body.appendChild(d1);
d1.innerHTML = dochtml;
var d2 = document.createElement("div");
d2.id = "d2";
d2.style.zIndex = 1;
d2.style.position = "absolute";
d2.style.width = "100%";
d2.style.height = "100%";
d2.style.left = "0px";
d2.style.top = "0px";
document.body.appendChild(d2);
return {d1: d1, d2: d2 };
}
function timeOuts(e, d1,d2)
{
setTimeout(function() { d1.className = e + " out"; }, 1);
setTimeout(function() { d2.className = e + " in"; }, 1);
setTimeout(function() {
document.body.innerHTML = d2.innerHTML;
cBa();
}, 706);
}
function slideTo(href, effect, pushstate)
{
var d = DE();
var d1 = d.d1;
var d2 = d.d2;
aDL(href, d2,
function() {
if (pushstate && window.history.pushState) window.history.pushState("", "", href);
timeOuts(effect,d1,d2);
}
);
}
function dC(e){ //Detect click event
var o;
var o=e.srcElement || e.target;
var tn = o.tagName.toLowerCase();
if (!but || tn!="input" || o.getAttribute("type")!="button") //if it is not a button
{
//try to find an anchor parent
while (tn!=="a" && tn!=="body")
{
o = o.parentNode;
tn = o.tagName.toLowerCase();
}
if (tn==="body") return;
}
var t = o.getAttribute("data-ftrans");
if (t)
{
e.preventDefault();
var hr = o.getAttribute("href") || o.getAttribute("data-href");
if (hr) slideTo(hr, t, true);
}
}
function aE(ev, el, f) { //Add event
if (el.addEventListener) // W3C DOM
el.addEventListener(ev,f,false);
else if (el.attachEvent) { // IE DOM
var r = el.attachEvent("on"+ev, f);
return r;
}
}
aE("click", window, dC);
aE(ol, document, //On load
function(ev)
{
aE("popstate", window, function(e) { //function to reload when back button is clicked
slideTo(location.pathname, navB, false);
});
}
);
}
here is the link to the site: http://www.fasw.ws/faswwp/non-jquery-page-transitions-lightweight/
I assume that thats not supposed to happen. So im trying to figure out how to keep it clean, and keep the head files loaded in the head, and only load the page content. I cannot figure this one out, some help from the pros is needed :)
FASW comes with two functions that serves as "hooks" both before and after initializing the component. you can do it like this:
(function inittrans()
{
initComponents();
var params = { /*put your options here*/ };
new ft(params);
})();
function onTransitionFinished()
{
initComponents();
}
function initComponents() {
// here is where you put your "other" javascript codes
}
Notice how your javascript codes are executed after loading your initial page and once again after the transition happened. Anyway, this is how I got the work around on it 'coz javascript codes just won't work as they are loaded by FASW via Ajax on-the-fly.

Categories

Resources