How to make multiple chunk of lines readonly in ace editor - javascript

I tried to make parts of code read-only in Ace editor.
I have tried by using code given in JsFiddle
$(function() {
var editor = ace.edit("editor1")
, session = editor.getSession()
, Range = require("ace/range").Range
, range = new Range(1, 4, 1, 10)
, markerId = session.addMarker(range, "readonly-highlight");
session.setMode("ace/mode/javascript");
editor.keyBinding.addKeyboardHandler({
handleKeyboard : function(data, hash, keyString, keyCode, event) {
if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;
if (intersects(range)) {
return {command:"null", passEvent:false};
}
}
});
before(editor, 'onPaste', preventReadonly);
before(editor, 'onCut', preventReadonly);
range.start = session.doc.createAnchor(range.start);
range.end = session.doc.createAnchor(range.end);
range.end.$insertRight = true;
function before(obj, method, wrapper) {
var orig = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
return wrapper.call(this, function(){
return orig.apply(obj, args);
}, args);
}
return obj[method];
}
function intersects(range) {
return editor.getSelectionRange().intersects(range);
}
function preventReadonly(next, args) {
if (intersects(range)) return;
next();
}
});
I got a problem when I keep pressing backspace it went into the read-only part and there was no editable part left.
How can I make multiple chunks of code read-only and avoid last character from read-only getting deleted.
Also, how to achieve the whole thing dynamically where I have markers in text specifying editable portions ?

Check the below code that allows multiple chunk of lines read-only with Enter at end of range to prevent non reversible delete and drag/drop handled.
function set_readonly(editor,readonly_ranges) {
var session = editor.getSession()
, Range = require("ace/range").Range;
ranges = [];
function before(obj, method, wrapper) {
var orig = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
return wrapper.call(this, function(){
return orig.apply(obj, args);
}, args);
}
return obj[method];
}
function intersects(range) {
return editor.getSelectionRange().intersects(range);
}
function intersectsRange(newRange) {
for (i=0;i<ranges.length;i++)
if(newRange.intersects(ranges[i]))
return true;
return false;
}
function preventReadonly(next, args) {
for(i=0;i<ranges.length;i++){if (intersects(ranges[i])) return;}
next();
}
function onEnd(position){
var row = position["row"],column=position["column"];
for (i=0;i<ranges.length;i++)
if(ranges[i].end["row"] == row && ranges[i].end["column"]==column)
return true;
return false;
}
function outSideRange(position){
var row = position["row"],column=position["column"];
for (i=0;i<ranges.length;i++){
if(ranges[i].start["row"]< row && ranges[i].end["row"]>row)
return false;
if(ranges[i].start["row"]==row && ranges[i].start["column"]<column){
if(ranges[i].end["row"] != row || ranges[i].end["column"]>column)
return false;
}
else if(ranges[i].end["row"] == row&&ranges[i].end["column"]>column){
return false;
}
}
return true;
}
for(i=0;i<readonly_ranges.length;i++){
ranges.push(new Range(...readonly_ranges[i]));
}
ranges.forEach(function(range){session.addMarker(range, "readonly-highlight");});
session.setMode("ace/mode/javascript");
editor.keyBinding.addKeyboardHandler({
handleKeyboard : function(data, hash, keyString, keyCode, event) {
if (Math.abs(keyCode) == 13 && onEnd(editor.getCursorPosition())){
return false;
}
if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;
for(i=0;i<ranges.length;i++){
if (intersects(ranges[i])) {
return {command:"null", passEvent:false};
}
}
}
});
before(editor, 'onPaste', preventReadonly);
before(editor, 'onCut', preventReadonly);
for(i=0;i<ranges.length;i++){
ranges[i].start = session.doc.createAnchor(ranges[i].start);
ranges[i].end = session.doc.createAnchor(ranges[i].end);
ranges[i].end.$insertRight = true;
}
var old$tryReplace = editor.$tryReplace;
editor.$tryReplace = function(range, replacement) {
return intersectsRange(range)?null:old$tryReplace.apply(this, arguments);
}
var session = editor.getSession();
var oldInsert = session.insert;
session.insert = function(position, text) {
return oldInsert.apply(this, [position, outSideRange(position)?text:""]);
}
var oldRemove = session.remove;
session.remove = function(range) {
return intersectsRange(range)?false:oldRemove.apply(this, arguments);
}
var oldMoveText = session.moveText;
session.moveText = function(fromRange, toPosition, copy) {
if (intersectsRange(fromRange) || !outSideRange(toPosition)) return fromRange;
return oldMoveText.apply(this, arguments);
}
}
function refresheditor(id,content,readonly) {
var temp_id=id+'_temp';
document.getElementById(id).innerHTML="<div id='"+temp_id+"'></div>";
document.getElementById(temp_id).innerHTML=content;
var editor = ace.edit(temp_id);
set_readonly(editor,readonly);
}
function get_readonly_by_editable_tag(id,content){
var text= content.split("\n");
var starts=[0],ends=[];
text.forEach(function(line,index){
if((line.indexOf("<editable>") !== -1))ends.push(index);
if((line.indexOf("</editable>") !== -1))starts.push(index+1);
});
ends.push(text.length);
var readonly_ranges=[];
for(i=0;i<starts.length;i++){
readonly_ranges.push([starts[i],0,ends[i],0])
}
refresheditor(id,content,readonly_ranges);
}
var content=document.getElementById("code").innerHTML;
function readonly_lines(id,content,line_numbers){
var readonly_ranges=[];
all_lines= line_numbers.sort();
for(i=0;i<line_numbers.length;i++){
readonly_ranges.push([line_numbers[i]-1,0,line_numbers[i],0]);
}
refresheditor(id,content,readonly_ranges);
}
get_readonly_by_editable_tag("myeditor",content)
//readonly_lines("myeditor",content,[5,7,9]);
.ace_editor {
width:100%;
height:300px;
}
.readonly-highlight{
background-color: red;
opacity: 0.2;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ace.c9.io/build/src/ace.js"></script>
<link rel="stylesheet" type="text/css" href="http://jsfiddle.net/css/normalize.css">
<link rel="stylesheet" type="text/css" href="http://jsfiddle.net/css/result-light.css">
<button onclick="get_readonly_by_editable_tag('myeditor',content)">Readonly by tags</button>
<button onclick="readonly_lines('myeditor',content,[3,7])">Readonly lines 3 and 7 </button>
<div id="myeditor" ></div>
<div id="code" style="display:none;">//<editable>
//</editable>
function refresheditor() {
//<editable>
document.getElementById("myeditor").innerHTML="<div id='editor'></div>";
document.getElementById("editor").innerHTML=document.getElementById("code").innerHTML;
//</editable>
var editor = ace.edit("editor")
, session = editor.getSession()
, Range = require("ace/range").Range;
ranges = [];
var text= document.getElementById("code").innerHTML.split("\n");
var starts=[0],ends=[];
text.forEach(function(line,index){
if((line.indexOf("&lt;editable&gt;") !== -1))ends.push(index);
if((line.indexOf("&lt;/editable&gt;") !== -1))starts.push(index+1);
});
ends.push(text.length);
for(i=0;i<starts.length;i++){
ranges.push(new Range(starts[i], 0,ends[i] ,0));
}
ranges.forEach(function(range){session.addMarker(range, "readonly-highlight");});
session.setMode("ace/mode/javascript");
//<editable>
editor.keyBinding.addKeyboardHandler({
handleKeyboard : function(data, hash, keyString, keyCode, event) {
var pos=editor.getCursorPosition();
if (Math.abs(keyCode) == 13){
for (i=0;i<ranges.length;i++){
if((ranges[i].end["row"]==pos["row"])&&(ranges[i].end["column"]==pos["column"])){ return false;}
}
}
if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;
for(i=0;i<ranges.length;i++){
if (intersects(ranges[i])) {
return {command:"null", passEvent:false};
}
}
}
});
//</editable>
before(editor, 'onPaste', preventReadonly);
before(editor, 'onCut', preventReadonly);
for(i=0;i<ranges.length;i++){
ranges[i].start = session.doc.createAnchor(ranges[i].start);
ranges[i].end = session.doc.createAnchor(ranges[i].end);
ranges[i].end.$insertRight = true;
}
function before(obj, method, wrapper) {
var orig = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
return wrapper.call(this, function(){
return orig.apply(obj, args);
}, args);
}
return obj[method];
}
function intersects(range) {
return editor.getSelectionRange().intersects(range);
}
function preventReadonly(next, args) {
for(i=0;i<ranges.length;i++){if (intersects(ranges[i])) return;}
next();
}
}
refresheditor();
</div>

This code snippet will prevent the user from editing the first or last line of the editor:
editor.commands.on("exec", function(e) {
var rowCol = editor.selection.getCursor();
if ((rowCol.row == 0) || ((rowCol.row + 1) == editor.session.getLength())) {
e.preventDefault();
e.stopPropagation();
}
});
https://jsfiddle.net/tripflex/y0huvc1b/
Source:
https://groups.google.com/forum/#!topic/ace-discuss/yffGsSG7GSA

sorry: this code does not handle drag/drop
I added this last proposal last week: Ace Editor: Lock or Readonly Code Segment

Related

Window.showModalDialog() does not work in a for loop JavaScript

I am trying to introduce showModaldialog in a for loop, I have changed the names of the id's so that, being different, it can be opened as many times as the user requests:
for (i = 0; i < number; i++) {
cerrado=0;
cerrado = window.showModalDialog(ventana, 'url' ,'nuevadiag'+id);
if (cerrado==null){
i=numero;
}
}
the problem is that it only opens once and nothing else, any ideas?, this is the jquery function of window.showModalDialog():
(function() {
window.spawn = window.spawn || function(gen) {
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (err) {
return Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
}
var generator = gen();
var onFulfilled = continuer.bind(continuer, 'next');
var onRejected = continuer.bind(continuer, 'throw');
return onFulfilled();
};
window.showModalDialog = window.showModalDialog || function(pantalla, url, arg, opt,id) {
//documento= window.parent.parent.document;
// alert(pantalla);
documento= pantalla.document;
// alert(documento.body);
url = url || ''; //URL of a dialog
arg = arg || null; //arguments to a dialog
opt = opt || 'dialogWidth:300px;dialogHeight:200px;color:#ff6600;'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
opt = opt+ ';color:#ff6600;';
var caller = '';
if(arguments.callee.caller != null ){
caller = arguments.callee.caller.toString();
}
var dialog = documento.body.appendChild(document.createElement('dialog'));
dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
dialog.setAttribute('id',id );
var idDialogClose="dialog-close"+id;
var idDialogBody = 'dialog-body';
if( id!=undefined && id!=null && id!=''){
var idDialogBody ='dialog-body'+id;
}
dialog.innerHTML = '×<iframe id="'+idDialogBody+'" src="' + url + '" style="border: 0; width: 100%; height: 100%;border-top: 3px solid #ff6600;border-bottom: 3px solid #ff6600;border-left: 3px solid #ff6600;border-right: 3px solid #ff6600;margin-right: -10px;margin-bottom: -10px;"></iframe>';
documento.getElementById(idDialogBody).contentWindow.dialogArguments = arg;
documento.getElementById(idDialogClose).addEventListener('click', function(e) {
e.preventDefault();
dialog.close();
});
dialog.showModal();
//if using yield or async/await
if(caller.indexOf('yield') >= 0 || caller.indexOf('await') >= 0) {
return new Promise(function(resolve, reject) {
dialog.addEventListener('close', function() {
var returnValue = documento.getElementById(idDialogBody).contentWindow.returnValue;
documento.body.removeChild(dialog);
//resolve(returnValue);
});
});
}
//if using eval
var isNext = false;
var nextStmts = caller.split('\n').filter(function(stmt) {
if(isNext || stmt.indexOf('showModalDialog(') >= 0)
return isNext = true;
return false;
});
dialog.addEventListener('close', function() {
var returnValue = documento.getElementById(idDialogBody).contentWindow.returnValue;
documento.body.removeChild(dialog);
alert('returnValue: '+returnValue);
alert('nextStmts: '+nextStmts);
alert('nextStmts[0]: '+nextStmts[0]);
alert('nextStmts[1]: '+nextStmts[1]);
nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
});
throw 'Execution stopped until showModalDialog is closed';
};
})();
thanks!
BR.

How to update function within another function in JavaScript?

How I can update function _handlePaste() inside function paste?
$.FE.MODULES.paste = function(editor) {
var clipboard_html;
function _handlePaste(e) {
// Read data from clipboard.
if (e && e.clipboardData && e.clipboardData.getData) {
var types = '';
var clipboard_types = e.clipboardData.types;
if (editor.helpers.isArray(clipboard_types)) {
for (var i = 0; i < clipboard_types.length; i++) {
types += clipboard_types[i] + ';';
}
} else {
types = clipboard_types;
}
clipboard_html = '';
// HTML.
if (/text\/html/.test(types)) {
clipboard_html = e.clipboardData.getData('text/html');
}
// Safari HTML.
else if (/text\/rtf/.test(types) && editor.browser.safari) {
clipboard_html = e.clipboardData.getData('text/rtf');
} else if (/text\/plain/.test(types) && !this.browser.mozilla) {
clipboard_html = editor.html.escapeEntities(e.clipboardData.getData('text/plain')).replace(/\n/g, '<br>');
}
if (clipboard_html !== '') {
_processPaste();
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
return false;
} else {
clipboard_html = null;
}
}
// Normal paste.
_beforePaste();
}
}
The function is the part of jquery plugin, so I would like to change the function outside of the plugin's files to be able further update it.
I am trying to change it like this:
(function ($) {
$.FE.MODULES.paste._handlePaste = function (e) {
// my implementation of _handlePaste
}
})(window.jQuery);
But I can't access _handlePaste this way.

Jquery quicksearch issue with Sharepoint 2013

I'm using a jquery plugin called quicksearch within Sharepoint 2010 and it works perfectly. Unfortunately were being forced to migrate onto sharepoint 2013 and it's stopped working. An error is shown saying that the function is undefined. I believe I've narrowed this down to the quicksearch function itself.
Here is the preliminary code:
_spBodyOnLoadFunctionNames.push("Load");
$('[name=search]').on('keyup', function(){
Load();
});
function Load() {
var searchArea = "#cbqwpctl00_ctl22_g_ca6bb172_1ab4_430d_ae38_a32cfa03b56b ul li";
var qs = $('input#id_search_list').val();
qs.quicksearch(searchArea);
$('.filter input').on('change', function(){
checkAndHide()
//$(searchArea).unhighlight();
});
function checkAndHide(){
var inputs = $('.filter input');
var i =0;
for (var i = 0; i < inputs.length; i++){
if (!inputs[i].checked){
$('.' + inputs[i].name).addClass('filter-hide');
} else {
$('.' + inputs[i].name).removeClass('filter-hide');
};
};
};
}
Here is an example of the quicksearch library I'm using:
(function($, window, document, undefined) {
$.fn.quicksearch = function (target, opt) {
var timeout, cache, rowcache, jq_results, val = '', e = this, options = $.extend({
delay: 300,
selector: null,
stripeRows: null,
loader: null,
noResults: 'div#noresults',
bind: 'keyup keydown',
onBefore: function () {
var ar = $('input#id_search_list').val()
if (ar.length > 2) {
var i=0;
var ar2 = $('input#id_search_list').val().split(" ");
for (i = 0; i < ar2.length; i++) {
$(searchArea + ':visible');
}
return true;
}
return false;
checkAndHide()
},
onAfter: function () {
return;
},
show: function () {
this.style.display = "block";
},
hide: function () {
this.style.display = "none";
},
prepareQuery: function (val) {
return val.toLowerCase().split(' ');
},
testQuery: function (query, txt, _row) {
for (var i = 0; i < query.length; i += 1) {
if (txt.indexOf(query[i]) === -1) {
return false;
}
}
return true;
}
}, opt);
this.go = function () {
var i = 0,
noresults = true,
query = options.prepareQuery(val),
val_empty = (val.replace(' ', '').length === 0);
for (var i = 0, len = rowcache.length; i < len; i++) {
if (val_empty) {
options.hide.apply(rowcache[i]);
noresults = false;
} else if (options.testQuery(query, cache[i], rowcache[i])){
options.show.apply(rowcache[i]);
noresults = false;
} else {
options.hide.apply(rowcache[i]);
}
}
if (noresults) {
this.results(false);
} else {
this.results(true);
this.stripe();
}
this.loader(false);
options.onAfter();
return this;
};
this.stripe = function () {
if (typeof options.stripeRows === "object" && options.stripeRows !== null)
{
var joined = options.stripeRows.join(' ');
var stripeRows_length = options.stripeRows.length;
jq_results.not(':hidden').each(function (i) {
$(this).removeClass(joined).addClass(options.stripeRows[i % stripeRows_length]);
});
}
return this;
};
this.strip_html = function (input) {
var output = input.replace(new RegExp('<[^<]+\>', 'g'), "");
output = $.trim(output.toLowerCase());
return output;
};
this.results = function (bool) {
if (typeof options.noResults === "string" && options.noResults !== "") {
if (bool) {
$(options.noResults).hide();
} else {
$(options.noResults).show();
}
}
return this;
};
this.loader = function (bool) {
if (typeof options.loader === "string" && options.loader !== "") {
(bool) ? $(options.loader).show() : $(options.loader).hide();
}
return this;
};
this.cache = function () {
jq_results = $(target);
if (typeof options.noResults === "string" && options.noResults !== "") {
jq_results = jq_results.not(options.noResults);
}
var t = (typeof options.selector === "string") ? jq_results.find(options.selector) : $(target).not(options.noResults);
cache = t.map(function () {
return e.strip_html(this.innerHTML);
});
rowcache = jq_results.map(function () {
return this;
});
return this.go();
};
this.trigger = function () {
this.loader(true);
if (options.onBefore()) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
e.go();
}, options.delay);
}
return this;
};
this.cache();
this.results(true);
this.stripe();
this.loader(false);
return this.each(function () {
$(this).bind(options.bind, function () {
val = $(this).val();
e.trigger();
});
});
};
}(jQuery, this, document));
`
This is where the error comes up:
var qs = $('input#id_search_list').val();
qs.quicksearch(searchArea);
Any help would be appreciated
Turns out was a small issue in the code and major css as sharepoint plays differently in 2013

PDF.js pages does not get painted. Only white pages are displayed

I am trying to render a pdf in chrome using PDFJS
This is the function I am calling:
open: function pdfViewOpen(url, scale, password) {
var parameters = {password: password};
if (typeof url === 'string') { // URL
this.setTitleUsingUrl(url);
parameters.url = url;
} else if (url && 'byteLength' in url) { // ArrayBuffer
parameters.data = url;
}
if (!PDFView.loadingBar) {
PDFView.loadingBar = new ProgressBar('#loadingBar', {});
}
this.pdfDocument = null;
var self = this;
self.loading = true;
getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
},
function getDocumentError(message, exception) {
if (exception && exception.name === 'PasswordException') {
if (exception.code === 'needpassword') {
var promptString = mozL10n.get('request_password', null,
'PDF is protected by a password:');
password = prompt(promptString);
if (password && password.length > 0) {
return PDFView.open(url, scale, password);
}
}
}
var loadingErrorMessage = mozL10n.get('loading_error', null,
'An error occurred while loading the PDF.');
if (exception && exception.name === 'InvalidPDFException') {
// change error message also for other builds
var loadingErrorMessage = mozL10n.get('invalid_file_error', null,
'Invalid or corrupted PDF file.');
//#if B2G
// window.alert(loadingErrorMessage);
// return window.close();
//#endif
}
var loadingIndicator = document.getElementById('loading');
loadingIndicator.textContent = mozL10n.get('loading_error_indicator',
null, 'Error');
var moreInfo = {
message: message
};
self.error(loadingErrorMessage, moreInfo);
self.loading = false;
},
function getDocumentProgress(progressData) {
self.progress(progressData.loaded / progressData.total);
}
);
}
This is the call:
PDFView.open('/MyPDFs/Pdf2.pdf', 'auto', null);
All I get is this:
If you notice, even the page number is retrieved but the content is not painted in the pages. Can´t find why.. Is the any other function I should call next to PDFView.open?
Found the solution...!
This is the code that does the work.
$(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

How can I fix this error "missing; before statement" in javascript?

How can I fix this error "missing; before statement" in javascript ?
My HTML Page :
http://etrokny.faressoft.com
My Javascript Code :
http://etrokny.faressoft.com/javascript.php
When assigning a function to a variable, you need a semicolon after the function.
Example: var func = function() { return false; };
Put a semicolon after all statements. JavaScript does it automatically for you when you "forget" one at the end of a line**, but since you used a tool to make everything fit on one line, this doesn't happen anymore.
** it should also be happening when a statement is followed by a }, but it's just bad practice to rely on it. I would always write all semicolons myself.
Actually, you know what, since it's so easy, I did it for you:
function getSelected() {
var selText;
var iframeWindow = window;
if (iframeWindow.getSelection) {
selText = iframeWindow.getSelection() + "";
} else if (iframeWindow.document.selection) {
selText = iframeWindow.document.selection.createRange().text;
}
selText = $.trim(selText);
if (selText != "") {
return selText;
} else {
return null;
}
}
$(document).ready(function () {
function scan_selectedText() {
if (getSelected() == null) {
return false;
}
if (getSelected().length < 25) {
return false;
}
$(document)[0].oncontextmenu = function () {
return false;
};
var result = true;
var selected_Text = getSelected();
selected_Text = selected_Text.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
$('#content .para').each(function () {
var accepted_text = $.trim($(this).text());
accepted_text = accepted_text.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
if (accepted_text.search(selected_Text) > -1) {
result = false;
}
});
var AllAccepted = "";
$('#content .para').each(function () {
var correntDiv = $.trim($(this).text()).replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
AllAccepted = AllAccepted + correntDiv + " ";
});
if ($.trim(AllAccepted).search(selected_Text) > -1) {
return false;
}
if (!result) {
return false;
}
var body = $.trim($('body').text());
body = body.replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' ');
var bodyWithoutDivs = body;
$('#content').each(function () {
var correntDiv = new RegExp($.trim($(this).text()).replace(/ {2,}/g, ' ').replace(/\s{2,}/g, ' '), "");
bodyWithoutDivs = bodyWithoutDivs.replace(correntDiv, '');
});
if (bodyWithoutDivs.search(selected_Text) > -1) {
return false;
}
if (body == selected_Text) {
return true;
}
return true;
}
$(document).mousedown(function (key) {
if (key.button == 2) {
if (scan_selectedText() == true) {
$(document)[0].oncontextmenu = function () {
return false;
};
} else {
$(document)[0].oncontextmenu = function () {
return true;
};
}
}
});
var isCtrl = false;
$(document).keyup(function (e) {
if (e.which == 17) isCtrl = false;
}).keydown(function (e) {
if (e.which == 17) isCtrl = true;
if (e.which == 67 && isCtrl == true) {
$("#content2").animate({
opacity: 0
}, 500).animate({
opacity: 1
}, 500);
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
}
});
document.onkeypress = function (evt) {
if (evt.ctrlKey == true && evt.keyCode == 67) {
$("#content2").animate({
opacity: 0
}, 500).animate({
opacity: 1
}, 500);
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
}
};
$('*').bind('copy', function (key) {
if (scan_selectedText() == true) {
return false;
} else {
return true;
}
});
});
First thing, start with the raw human-written version of your javascript, you know, the unminimized non-machine-generated version
After you've fixed you've made sure it is free from syntax errors .... and you minimize it, don't make a mistake when copy/pasting

Categories