Why function(document) doesn't work in separate file? - javascript

I have an HTML file and this contain JavaScript code and works fine, but when I decided put the JS code in different file and call from the HTML file, doesn't work. Why?
The JS code is like this:
(function (document) {
var toggleDocumentationMenu = function () {
var navBtn = document.querySelector('.main-nav1');
var navList = document.querySelector('.main-nav2');
var navIsOpenedClass = 'nav-is-opened';
var navListIsOpened = false;
navBtn.addEventListener('click', function (event) {
event.preventDefault();
if (!navListIsOpened) {
addClass(navList, navIsOpenedClass);
navListIsOpened = true;
} else {
removeClass(navList, navIsOpenedClass);
navListIsOpened = false;
}
});
};
var toggleMainNav = function () {
var documentationItem = document.querySelector('.main-nav3');
var documentationLink = document.querySelector('.main-nav3 > .main-sub-nav');
var documentationIsOpenedClass = 'subnav-is-opened';
var documentationIsOpened = false;
if (documentationLink) {
documentationLink.addEventListener('click', function (event) {
event.preventDefault();
if (!documentationIsOpened) {
documentationIsOpened = true;
addClass(documentationItem, documentationIsOpenedClass);
} else {
documentationIsOpened = false;
removeClass(documentationItem, documentationIsOpenedClass);
}
});
}
};
var isTouch = function () {
return ('ontouchstart' in window) ||
window.DocumentTouch && document instanceof DocumentTouch;
};
var addClass = function (element, className) {
if (!element) {
return;
}
element.className = element.className.replace(/\s+$/gi, '') + ' ' + className;
};
var removeClass = function (element, className) {
if (!element) {
return;
}
element.className = element.className.replace(className, '');
};
toggleDocumentationMenu();
toggleMainNav();
})(document);
I read it's possible that works if I put like this:
$(document).ready(function() {
// the javascript code here
});
But it still doesn't working.
Now I wonder, It's possible this code works fine in separate file?

Related

Jquery plugin is not working and causing console errors, how do I fix?

I installed Shuffle.js from a codepen demo with some customizations to style and figure cards. I've added in recommended js code but the shuffle function doesn't seem work.
Getting several errors:
console errors
I've tried updating script based on some past answers to this problem. I've also downloaded and added the actual js file on my site and referenced it in the script. Here's what my script looks like right now:
<script src="/v/vspfiles/assets/js/shuffle.js"></script>
<script>
'use strict';
var Shuffle = window.shuffle;
var Demo = function (element) {
this.element = element;
// Log out events.
this.addShuffleEventListeners();
this.shuffle = new Shuffle(element, {
itemSelector: '.picture-item',
sizer: element.querySelector('.my-sizer-element'),
});
this._activeFilters = [];
this.addFilterButtons();
this.addSorting();
this.addSearchFilter();
this.mode = 'exclusive';
};
Demo.prototype.toArray = function (arrayLike) {
return Array.prototype.slice.call(arrayLike);
};
Demo.prototype.toggleMode = function () {
if (this.mode === 'additive') {
this.mode = 'exclusive';
} else {
this.mode = 'additive';
}
};
/**
* Shuffle uses the CustomEvent constructor to dispatch events. You can listen
* for them like you normally would (with jQuery for example). The extra event
* data is in the `detail` property.
*/
Demo.prototype.addShuffleEventListeners = function () {
var handler = function (event) {
console.log('type: %s', event.type, 'detail:', event.detail);
};
this.element.addEventListener(Shuffle.EventType.LAYOUT, handler, false);
this.element.addEventListener(Shuffle.EventType.REMOVED, handler, false);
};
Demo.prototype.addFilterButtons = function () {
var options = document.querySelector('.filter-options');
if (!options) {
return;
}
var filterButtons = this.toArray(
options.children
);
filterButtons.forEach(function (button) {
button.addEventListener('click', this._handleFilterClick.bind(this), false);
}, this);
};
Demo.prototype._handleFilterClick = function (evt) {
var btn = evt.currentTarget;
var isActive = btn.classList.contains('active');
var btnGroup = btn.getAttribute('data-group');
// You don't need _both_ of these modes. This is only for the demo.
// For this custom 'additive' mode in the demo, clicking on filter buttons
// doesn't remove any other filters.
if (this.mode === 'additive') {
// If this button is already active, remove it from the list of filters.
if (isActive) {
this._activeFilters.splice(this._activeFilters.indexOf(btnGroup));
} else {
this._activeFilters.push(btnGroup);
}
btn.classList.toggle('active');
// Filter elements
this.shuffle.filter(this._activeFilters);
// 'exclusive' mode lets only one filter button be active at a time.
} else {
this._removeActiveClassFromChildren(btn.parentNode);
var filterGroup;
if (isActive) {
btn.classList.remove('active');
filterGroup = Shuffle.ALL_ITEMS;
} else {
btn.classList.add('active');
filterGroup = btnGroup;
}
this.shuffle.filter(filterGroup);
}
};
Demo.prototype._removeActiveClassFromChildren = function (parent) {
var children = parent.children;
for (var i = children.length - 1; i >= 0; i--) {
children[i].classList.remove('active');
}
};
Demo.prototype.addSorting = function () {
var menu = document.querySelector('.sort-options');
if (!menu) {
return;
}
menu.addEventListener('change', this._handleSortChange.bind(this));
};
Demo.prototype._handleSortChange = function (evt) {
var value = evt.target.value;
var options = {};
function sortByDate(element) {
return element.getAttribute('data-created');
}
function sortByTitle(element) {
return element.getAttribute('data-title').toLowerCase();
}
if (value === 'date-created') {
options = {
reverse: true,
by: sortByDate,
};
} else if (value === 'title') {
options = {
by: sortByTitle,
};
}
this.shuffle.sort(options);
};
// Advanced filtering
Demo.prototype.addSearchFilter = function () {
var searchInput = document.querySelector('.js-shuffle-search');
if (!searchInput) {
return;
}
searchInput.addEventListener('keyup', this._handleSearchKeyup.bind(this));
};
/**
* Filter the shuffle instance by items with a title that matches the search input.
* #param {Event} evt Event object.
*/
Demo.prototype._handleSearchKeyup = function (evt) {
var searchText = evt.target.value.toLowerCase();
this.shuffle.filter(function (element, shuffle) {
// If there is a current filter applied, ignore elements that don't match it.
if (shuffle.group !== Shuffle.ALL_ITEMS) {
// Get the item's groups.
var groups = JSON.parse(element.getAttribute('data-groups'));
var isElementInCurrentGroup = groups.indexOf(shuffle.group) !== -1;
// Only search elements in the current group
if (!isElementInCurrentGroup) {
return false;
}
}
var titleElement = element.querySelector('.picture-item__title');
var titleText = titleElement.textContent.toLowerCase().trim();
return titleText.indexOf(searchText) !== -1;
});
};
document.addEventListener('DOMContentLoaded', function () {
window.demo = new Demo(document.getElementById('grid'));
});
</script>
Any insight into what I need to remedy to get this working properly would be great. Thanks!

How to check if a function has been called before executing another function everytime

I have a onMouseDownEssence() and onMouseUpEssence() function for an HTML element, how to check if onMouseDownEssence() is called every time before calling onMouseUpEssence() to ensure I get the correct mouse down position?
Here is mousedown function:
var mouseDownIndex = -1;
function onMouseDownEssence(downIndex, e, className) {
dragTarget = e.target;
holdStarter = new Date().valueOf();
mouseDownIndex = downIndex;
}
Here is mouseup function:
function onMouseUpEssence(upIndex, e, className) {
var el = e.target;
var holdActive = (new Date().valueOf() - holdStarter) > holdDelay;
if (holdActive) {
var thisUpTargetIndex = el.getAttribute("name");
if (lastUpTargetIndex != null && thisUpTargetIndex != lastUpTargetIndex) {
// console.log("double drag done");
el.removeAttribute(dbl);
lastUpTargetIndex = null;
var selectedText = clickDragAutoExpand(mouseDownIndex, upIndex,
className);
} else {
// console.log("drag done");
var selectedText = clickDragAutoExpand(mouseDownIndex, upIndex,
className);
}
holdActive = false;
} else if (el.getAttribute(dbl) == null) {
el.setAttribute(dbl, 1);
setTimeout(
function() {
if (el.getAttribute(dbl) == 1 && !dragTarget) {
if (e.button === 0) {
// console.log("single clicked ");
el.removeAttribute(dbl);
var selectedText = clickAutoExpand(upIndex,
className);
}
} else {
if (el.getAttribute(dbl) != null)
lastUpTargetIndex = el.getAttribute("name");
}
}, dblDelay);
} else {
// console.log("double clicked");
el.removeAttribute(dbl);
var selectedText = clickAutoExpand(upIndex, className);
}
dragTarget = null;
}
My approach would be to keep a track of whether mouseDownEssence() was called. And if not, call it before proceeding further. This approach would work somewhat as below. It would work differently for asynchronous functions but mouseDownEssence() seems to be a synchronous function.
let isMouseDownEssenceCalled = false;
function mouseDownEssence() {
isMouseDownEssenceCalled = true;
...
}
function mouseUpEssence() {
if (!isMouseDownEssenceCalled) {
mouseDownEssence()
}
...
isMouseDownEssenceCalled = false;
}

Closing a menu on anywhere click

I am working on a website and here is the link file:///D:/fahim/HTML/menu/index.html. If you click the menu its closing on its own "X" button, but i want it to close by clicking outside the menu. This is the javascript used on the home page.
<script>
var popupView = new popup();
document.querySelector('#btn_1').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_1'));
});
document.querySelector('#btn_2').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_2'), function () {
console.log('show do something');
});
});
document.querySelector('#btn_3').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_3'), '', function () {
console.log('CLOSE');
});
});
</script>
And this is the code which is attached as popup_view.js file on server
(function () {
var popup = function() {
function hide(dom, dosomething) {
if (!dom) {
console.error('hide function not set dom object');
return;
}
if (dosomething) {
dosomething();
}
dom.className += ' ' + 'popup_hide';
}
function show(dom, dosomethingShow, dosomethingClose) {
if (!dom) {
console.error('show function not set dom object');
return;
}
if (dosomethingShow) {
dosomethingShow();
}
var className = 'popup_hide',
reg = new RegExp('(^|\\b)' +
className.split(' ').join('|') +
'(\\b|$)', 'gi');
dom.className = dom.className.replace(reg, '').trim();
var nodes = dom.childNodes;
for (var i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].className === 'pop_up_close') {
var close = function (e) {
if (dosomethingClose) {
dosomethingClose();
}
dom.className += ' ' + 'popup_hide';
nodes[i].removeEventListener('click', close);
};
nodes[i].addEventListener('click', close);
break;
}
}
}
this.show = show;
this.hide = hide;
};
window.popup = popup;
})();
Please help as i have tried lot of codes except these but non of them works
$(document).on('click', function(e){
//your close function
e.stopPropagation();
}
Put that code anywhere in your $(document).ready(... block

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');
}
}

Manually calling PDFJS functions. What func to call after PDFView.open to render

CanĀ“t find in the documentation what to do next.
Calling:
PDFView.open('/MyPDFs/Pdf1.pdf', 'auto', null)
I am able to see the blank pages, the loader and also the document gets the number of pages of my PDF.
The only thing is missing is the rendering.
Does anyone knows what I should call next?
Thanks
$(document).ready(function () {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
//#if !(FIREFOX || MOZCENTRAL)
var file = params.file || DEFAULT_URL;
//#else
//var file = window.location.toString()
//#endif
//#if !(FIREFOX || MOZCENTRAL)
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
//#else
//document.getElementById('openFile').setAttribute('hidden', 'true');
//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = PDFView.parseQueryString(hash);
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
//#if !(FIREFOX || MOZCENTRAL)
var locale = navigator.language;
if ('locale' in hashParams)
locale = hashParams['locale'];
mozL10n.setLanguage(locale);
//#endif
if ('textLayer' in hashParams) {
switch (hashParams['textLayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textLayer']);
break;
}
}
//#if !(FIREFOX || MOZCENTRAL)
if ('pdfBug' in hashParams) {
//#else
//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
}
if (!PDFView.supportsFullscreen) {
document.getElementById('fullscreen').classList.add('hidden');
}
if (PDFView.supportsIntegratedFind) {
document.querySelector('#viewFind').classList.add('hidden');
}
// Listen for warnings to trigger the fallback UI. Errors should be caught
// and call PDFView.error() so we don't need to listen for those.
PDFJS.LogManager.addLogger({
warn: function () {
PDFView.fallback();
}
});
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function (e) {
if (e.target == mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function () {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFView.sidebarOpen = outerContainer.classList.contains('sidebarOpen');
PDFView.renderHighestPriority();
});
document.getElementById('viewThumbnail').addEventListener('click',
function () {
PDFView.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function () {
PDFView.switchSidebarView('outline');
});
document.getElementById('previous').addEventListener('click',
function () {
PDFView.page--;
});
document.getElementById('next').addEventListener('click',
function () {
PDFView.page++;
});
document.querySelector('.zoomIn').addEventListener('click',
function () {
PDFView.zoomIn();
});
document.querySelector('.zoomOut').addEventListener('click',
function () {
PDFView.zoomOut();
});
document.getElementById('fullscreen').addEventListener('click',
function () {
PDFView.fullscreen();
});
document.getElementById('openFile').addEventListener('click',
function () {
document.getElementById('fileInput').click();
});
document.getElementById('print').addEventListener('click',
function () {
window.print();
});
document.getElementById('download').addEventListener('click',
function () {
PDFView.download();
});
document.getElementById('pageNumber').addEventListener('change',
function () {
PDFView.page = this.value;
});
document.getElementById('scaleSelect').addEventListener('change',
function () {
PDFView.parseScale(this.value);
});
document.getElementById('first_page').addEventListener('click',
function () {
PDFView.page = 1;
});
document.getElementById('last_page').addEventListener('click',
function () {
PDFView.page = PDFView.pdfDocument.numPages;
});
document.getElementById('page_rotate_ccw').addEventListener('click',
function () {
PDFView.rotatePages(-90);
});
document.getElementById('page_rotate_cw').addEventListener('click',
function () {
PDFView.rotatePages(90);
});
//#if (FIREFOX || MOZCENTRAL)
//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
// PDFView.setTitleUsingUrl(file);
// PDFView.initPassiveLoading();
// return;
//}
//#endif
//#if !B2G
PDFView.open(file, 0);
//#endif
});
The system must be initialized first before PDFView.open call! Thanks
In viewer.js I added call to updateViewarea() after the document was downloaded.
... PDFJS.getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
updateViewarea();
}, ...

Categories

Resources