How to destroy PDFJS object? - javascript

I need functionality for book library and for that I have used:
Turn.js, which is used for flipbook effect (only 3rd release working, 4th release not working with it, if someone have similar functionality with 4th release of turn.js, then please share your code).
pdf.js, which converts PDF to HTML on client side
This is a reference link, that I have followed.
I have modified one function for using that script dynamically, which adds PDF's path into that function and according to that link, books open in popup.
Here is the JavaScript function for that:
function display_book(path){
var url = path;
PDFJS.disableWorker = false;
PDFJS.getDocument(url).then(function(pdfDoc) {
numberOfPages = pdfDoc.numPages;
pdf = pdfDoc;
$('#book').turn.pages = numberOfPages;
$('#book').turn({acceleration: false,
pages: numberOfPages,
elevation: 50,
gradients: !$.isTouch,
// display: 'single',
when: {
turning: function(e, page, view) {
// Gets the range of pages that the book needs right now
var range = $(this).turn('range', page);
// Check if each page is within the book
for (page = range[0]; page<=range[1]; page++) {
addPage(page, $(this));
//renderPage(page);
};
},
turned: function(e, page) {
$('#page-number').val(page);
if (firstPagesRendered) {
var range = $(this).turn('range', page);
for (page = range[0]; page<=range[1]; page++) {
if (!rendered[page]) {
renderPage(page);
rendered[page] = true;
}
};
}
}
}
});
$("button.close").click(function(){
//code for destroy pdfjs object
$(".modal").css({"display":"none"});
});
});
}
on that popup close event, I want to destroy object of PDFJS (to release memory). In this code turn.js 3rd released version is used, and if I replace that version with 4th release then code doesn't work.

You just need to call destroyon the pdfDoc instance.
In your code sample, it looks like pdfDoc is assign to the global variable pdf. So, this should do what you want:
pdf.destroy();

Related

JQuery function - Run it automatically once a day instead of a on click action

We have a WordPress theme serving as an online directory. This theme uses a JSON file to display our listings on our map. For each of our modifications on a listing we must click on a button named "JSON Generator" to update the data of the map.
The problem is that we are currently adding/modifying a lot of content on our map so it requires a lot of manual regenerations.
Screenshot of the button and the HTML declaration
Is there a way to replace the click launch of the JavaScript function regenerating the JSON by an automatic launch every 24 hours for example?
Here is the start of my actual .js file :
;(function($) {
// Json Generator
var directoryManagerAdmin = function() {
this.param = lava_dir_admin_param;
this.init();
}
directoryManagerAdmin.prototype.constructor = directoryManagerAdmin;
directoryManagerAdmin.prototype.init = function() {
var self = this;
$(document)
.on('click', '.lava-data-refresh-trigger', this.onGenerator())
.on('click', '.fileupload', this.image_upload())
.on('click', '.fileuploadcancel', this.image_remove())
$('button[data-listing-type-generator]').each(function() {
var listingType = $(this).data('listing-type-generator') || false;
var Instance = self.onGenerator(listingType);
$(this).on('click', Instance);
});
self.bindJsonEditor();
}
directoryManagerAdmin.prototype.onGenerator = function(type) {
// THEN YOU HAVE THE VERY LONG FUNCTION...
I think that I have to replace the launcher: .on( 'click', '.lava-data-refresh-trigger', this.onGenerator() ) with an automatic launcher every 24 hours or so.
I found out how to get the current date: var date = new Date().toLocaleDateString();, I also know that I may have to use the setInterval action but I don't know how to use it.
Thanks by advance if you have any clue to help me !

Trying to move an element created after document load into another element

I'm working on this website: https://nuebar.com/ and I've just installed an app by shopify the places their currency selector right at the very bottom of the site, and I'm trying to move it into a div class .CSPosition that's been placed in a list item next to the current currency selector in the header.
Doing this because none of my international customers are finding the selector at the bottom of the site and the one at the top of the site doesn't change checkout currency, so will be removing it once I can move the one at the bottom successfully.
I've written this:
document.getElementsByClassName("locale-selectors__container").addEventListener("load", moveUp);
function moveUp () {
"use strict";
$(".locale-selectors__container").insertBefore(".CSPosition");
}
to try and move it once it's been loaded since it's being loaded by a third party but it's not working.
I've also tried:
$(".locale-selectors__container").load(function(){
$(".locale-selectors__container").insertBefore(".CSPosition");
});
I've also tried doing it when everything has loaded:
$( window ).on(function(){
$(".locale-selectors__container").insertBefore(".CSPosition");
});
Is it because of limitations with elements inserted by a third party of am I making stupid mistakes? Is there something wrong with my two methods?
setTimeout example
document.addEventListener('DOMContentLoaded', (event) => {
waitForSource();
});
function waitForSource(){
setTimeout(function(){
const source = document.querySelector('.locale-selectors__container');
if (!source) {
waitForSource();
}else{
const destination = document.querySelector('.CSPosition');
destination.append(source);
}
}, 350);
}
setInterval example
let checkSourceInterval = null;
document.addEventListener('DOMContentLoaded', (event) => {
checkSourceInterval = setInterval(() => {
const source = document.querySelector('.locale-selectors__container');
if (!!source) {
const destination = document.querySelector('.CSPosition');
destination.append(source);
clearInterval(checkSourceInterval);
}
}, 350);
});
I ended up with this:
setTimeout(function(){
console.log('DOM fully loaded and parsed');
const source = document.querySelector('.locale-selectors__container');
const destination = document.querySelector('.CSPosition');
destination.append(source);
}, 5000);
The setTimeout was the only way to circumvent and document/window/DOM loads that the app has on their end.
Now onto styling.

YUI Library - Best way to keep global reference to object?

I'm trying to use the yahoo ui history library. I don't see a great way to avoid wrapping all my function contents with the Y.use so that I can get access to the history object. I tried declaring it globally outside of the use() command, but this didn't seem to work. If you look at my showDashboard() and showReport1() methods, you can see I'm wrapping the contents, which seems redundant to have to do this for every function that uses the history. Is there a better way to do this?
All of the yahoo examples I've seen don't se functions at all and keep the entire sample inside a single use method.
<div>
Dashboard |
Report 1
</div>
<script type="text/javascript">
// Global reference to Yahoo UI object
var Y = YUI();
function showDashboard() {
Y.use('*', function (Y) {
var history = new Y.HistoryHash();
history.addValue("report", "dashboard");
});
}
function showReport1() {
Y.use('*', function (Y) {
var history = new Y.HistoryHash();
history.addValue('report', "report1");
//var x = { 'report': 'report1', 'date': '11/12/2012' };
//history.addValue("report", x);
});
}
Y.use('history', 'tabview', function (Y) {
var history = new Y.HistoryHash();
var tabview = new Y.TabView({ srcNode: '#demo' });
// Render the TabView widget to turn the static markup into an
// interactive TabView.
tabview.render();
// Set the selected report to the bookmarked history state, or to
// the first report if there's no bookmarked state.
tabview.selectChild(history.get('report') || 0);
// Store a new history state when the user selects a report.
tabview.after('selectionChange', function (e) {
// If the new tab index is greater than 0, set the "tab"
// state value to the index. Otherwise, remove the "tab"
// state value by setting it to null (this reverts to the
// default state of selecting the first tab).
history.addValue('report', e.newVal.get('index') || 0);
});
// Listen for history changes from back/forward navigation or
// URL changes, and update the report selection when necessary.
Y.on('history:change', function (e) {
// Ignore changes we make ourselves, since we don't need
// to update the selection state for those. We're only
// interested in outside changes, such as the ones generated
// when the user clicks the browser's back or forward buttons.
if (e.src === Y.HistoryHash.SRC_HASH) {
if (e.changed.report) {
// The new state contains a different report selection, so
// change the selected report.
tabview.selectChild(e.changed.report.newVal);
} else if (e.removed.report) {
// The report selection was removed in the new state, so
// select the first report by default.
tabview.selectChild(0);
}
}
if (e.changed.report) {
alert("New value: " + e.changed.report.newVal);
alert("Old value: " + e.changed.report.prevVal);
}
});
});
</script>
</form>
</body>
</html>
Instead of using plain function on click, attach handlers with YUI.
If you can change the HTML code - add id or class to the links, for example
<a id="btnShowDashboard" href="#">Dashboard</a>
Then in your use() add click handler to the buttons
Y.use('history', 'tabview', 'node', 'event', function (Y) {
var bntShowDashboard = Y.one('#btnShowDashboard');
if (bntShowDashboard) {
bntShowDashboard.on('click', function(e) {
e.preventDefault();
var history = new Y.HistoryHash();
history.addValue("report", "dashboard");
});
}
...
})
That way you will be sure than on the moment of execution "history" is loaded.
BUT there is one drawback - until YUI modules are loaded, if you click the links nothing will happen.

Excel like behavior with SlickGrid

I'd like to mimic a particular behavior of spreadsheets with SlickGrid. The user:
clicks on a cell to activate it
enters =sum(, or whatever formula,
the original cell address is saved
the user selects the cell range (I assume that the original cell closes the editor)
focus is returned to the original cell with the new cell range appended. i.e. =sum(r1c1,r2c2).
What's throwing me off is the need to change focus.
var cell_with_formula = null;
grid = new Grid($("#myGrid"), data, columns, options);
// save original cell address, but there is no onBlur event
grid.onBlur = function(args){
cell_with_formula = args; // save address
};
grid.onCellRangeSelected = function(){
if(cell_with_formula){
// check if cell_with_formula has `=` at begining
// if so, append selected range
cell_with_formula = null;
}
};
Thanks in advance!
This is not possible in SlickGrid 1.4.x, but is going to be supported in the version 2.0 that is currently still under active development. The alpha is hosted in a separate branch on GitHub - https://github.com/mleibman/SlickGrid/tree/v2.0a, and I just checked in preliminary code that supports this with an example. Please see https://github.com/mleibman/SlickGrid/commit/17b1bb8f3c43022ee6aec89dcab185cd368b8785.
Here's a basic formula editor implementation:
function FormulaEditor(args) {
var _self = this;
var _editor = new TextCellEditor(args);
var _selector;
$.extend(this, _editor);
function init() {
// register a plugin to select a range and append it to the textbox
// since events are fired in reverse order (most recently added are executed first),
// this will override other plugins like moverows or selection model and will
// not require the grid to not be in the edit mode
_selector = new Slick.CellRangeSelector();
_selector.onCellRangeSelected.subscribe(_self.handleCellRangeSelected);
args.grid.registerPlugin(_selector);
}
this.destroy = function() {
_selector.onCellRangeSelected.unsubscribe(_self.handleCellRangeSelected);
grid.unregisterPlugin(_selector);
_editor.destroy();
};
this.handleCellRangeSelected = function(e, args) {
_editor.setValue(_editor.getValue() + args.range);
};
init();
}

JQuery/Javascript works on & off

I am using JQuery 1.3.2-min in a project to handle JavaScript animations, ajax, etc. I have stored the file on the same server as the site instead of using Google. When I run the site locally on my development machine, everything works fine in FF, IE, Opera, and Safari (all the latest versions - I work from home and I only have 1 machine for personal use and development use) except for some CSS differences between them and when I go to the live site on my machine it works fine also. I have cleared my caches and hard refreshed the page, and it still works.
This is where it gets interesting however. When I send the site to my boss to test in various OS/Browser configurations, one page doesn't work correctly, some of it works, some doesn't. Also, the client (who uses IE 8) has also confirmed that it is not completely working - in fact he has told me that the page will work fine for a hour, and then just "turn off" for a while. I have never heard of this sort of thing before, and google isn't turning too much up. I have a hunch it may partly be with JQuery's .data(), but I'm not sure.
The page is basically nested unordered lists, and three basic actions happen on the list.
The top most unordered list is set to visible (all list via css are set to display: none to keep them hidden on a fresh page request); all list items divs are given a hover action of full opacity on mouseon, and faded back to 50% opacity on mouseoff; and then whenver a paragraph is clicked, the top most unordered list in that list item is displayed.
Here is my Javascript file for the page:
$(function() {
// Set first level ul visible
$('div#pageListing ul:first').css('display', 'block');
// Disable all the hyperlinks in the list
$('div#pageListing li a').click(function() {
var obj;
obj = $(this).parent(0).parent('div:first');
highlight(obj);
return false;
});
// List Item mouse hovering
$('#pageListing li').hover(
// Mouse On
function() {
if ($(this).children('div').attr('id') !== 'activePage') {
$(this).children('div').css('opacity', 1).css('filter',
'alpha(opacity=100)');
}
}, // Mouse off
function() {
if ($(this).children('div').attr('id') !== 'activePage') {
$(this).children('div').css('opacity', 0.4).css('filter',
'alpha(opacity=40)');
}
});
// Active list item highlighting
$('#pageListing li div').click(function() {
highlight($(this));
});
// Sub-list expanding/collapsing
$('#pageListing p.subpageslink').click(function() {
// Get next list
var subTree = $(this).parent('div').next('ul');
// If list is currently active, close it, else open it.
if (subTree.data('active') != true) {
subTree.data('active', true);
subTree.show(400);
} else {
subTree.data('active', false);
subTree.hide(400);
}
});
// Double clicking of list item - edit a page
$('#pageListing li div').dblclick(function() {
var classes = $(this).attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
editPage(pageID);
});
// Handle button clicking
$('button#addPage').click(function() {
addPage();
});
$('button#editPage').click(function() {
var div = $('div#activePage');
var classes = div.attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
editPage(pageID);
});
$('button#delPage').click(function() {
var div = $('div#activePage')
var classes = div.attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
delPage(pageID);
});
});
// Highlighting of page when clicked
function highlight(obj) {
// Get previous hightlighted element
// and un-highlight
var oldElement = $('div#activePage');
oldElement.css('background', 'white');
oldElement.css('opacity', 0.4).css('filter', 'alpha(opacity=40)');
oldElement.removeAttr('id');
// highlight current selection
obj.attr('id', 'activePage');
obj.css('opacity', 1).css('filter', 'alpha(opacity=100)');
obj.css('background', '#9dc0f4');
// add appropiate action buttons
$('button.pageButton').css('display', 'inline');
}
function addPage() {
window.location = "index.php?rt=cms/editPage";
}
function delPage(page) {
var confirm = window.confirm("Are you sure? Any sub-pages WILL BE deleted also.");
if (confirm) {
var url = './components/cms/controller/forms/deletePage.php';
$.ajax( {
url : url,
type : 'GET',
data : 'id=' + page,
success : function(result) {
if (!result) {
document.location = "index.php?rt=cms";
} else {
window.alert('There was a problem deleting the page');
}
}
});
}
}
function editPage(page) {
var url = "index.php?rt=cms/editPage/" + page;
window.location = url;
}
Is it possible that you are linking to (some of) the script files using a src that points to a file on your local disk/HDD? If so, that would explain why it works only on your machine, as then only your machine has access to the script file.
Thank you one and all for your suggestions. The end problem was miscommunication. I work from home, and upload my projects to a SVN server, which the boss then uses to update the live server. Somehow, the correct files were not getting updated - a communication error on my part. Another possible reason was that the page, while being declared XHTML 1.0 Strict, had something like 50 validation errors (mosting incorrectly nested UL), and I cleaned that up to 5 errors. So thank you all, but again a sad example of the importance of team work communication.

Categories

Resources