Wait for in javascript - javascript

I have a JavaScript function that updates my data.
The user may Click several times and I want to Wait for the Second click while the first click is not finished and so on
$scope.isLastUpdateFinished = true;
$scope.onSave = function (isFitToPage) {
if (!$scope.isLastUpdateFinished)
while (!$scope.isLastUpdateFinished) {
}
$scope.isLastUpdateFinished = false;
dataService.save($scope.draft, "api/Draft/UpdateDraft/").then(function (data) {
if (data.Succeeded && data.Message != null)
toaster.pop("warning", _("Dataservice_TTL_Save"), data.Message);
if (!data.Succeeded) {
modalOptions.headerText = _("Error_InRefreshList");
modalOptions.bodyText = data.Message;
modalService.showModal(errorDefaults, modalOptions);
}
if (isFitToPage) {
$scope.imageviewer.viewerconfig.controls.imageReload(true, true);
}
if ($scope.myOtherAside.$scope.$isShown && isFitToPage) {
$scope.viewerconfig.controls.imageReload(true, true);
}
$scope.isLastUpdateFinished = true;
});
};

How about just notifying the user that the app is still working?
$scope.isLastUpdateFinished = true;
$scope.onSave = function (isFitToPage) {
if (!$scope.isLastUpdateFinished)
{
toaster.pop("info", "Please wait...", "Request already in progress... ");
return false;
}
$scope.isLastUpdateFinished = false;
dataService.save($scope.draft, "api/Draft/UpdateDraft/").then(function (data) {
if (data.Succeeded && data.Message != null)
toaster.pop("warning", _("Dataservice_TTL_Save"), data.Message);
if (!data.Succeeded) {
modalOptions.headerText = _("Error_InRefreshList");
modalOptions.bodyText = data.Message;
modalService.showModal(errorDefaults, modalOptions);
}
if (isFitToPage) {
$scope.imageviewer.viewerconfig.controls.imageReload(true, true);
}
if ($scope.myOtherAside.$scope.$isShown && isFitToPage) {
$scope.viewerconfig.controls.imageReload(true, true);
}
$scope.isLastUpdateFinished = true;
});
};

Related

Socket.io and Angular.js chat script TimeOut

I am trying to get my chat script to work I have moved to a VPS thinking that should solve any missing extensions but I have the same problem.
A user logs into the website and can then load the chat to talk with other members - I am using the datingframework
in the console window I can see the message but socket.io keeps timing out I have tried using different ports and changing from https - http but get the same error
On their demo website when I send a chat I notice a different scroll event getting triggered before the message is displayed.
This is some of the chat js code as there is a limit on the amount I can post!!
/* this is main chat controller */
App.controller('WebsocketChatController',function($scope,$rootScope,$http, socket, $timeout,$location,$anchorScroll,Upload,$log,$timeout,screenSize) {
$scope.getSocketObj= function()
{
return socket;
}
/* socket operations */
$scope.socket_id = 0;
socket.on('connected', function(data){
$scope.socket_id = data.socket_id;
$scope.mapUserWithSocket();
});
//if not in chatUsers array take from ajax call
socket.on("new_message_received", function(data){
//$scope.getChatUsers();
var text = parseInt($(".notification-message").html());
if(isNaN(text)){
text= 0;
}
$(".notification-message").html(text+1);
console.log(JSON.stringify(data));
toastr.success(recieved_msg);
var user = $scope.findUserByID(data.from_user);
//toastr.success('You got a new message from '+user.user.name);
if(data.to_user==$scope.authUser)
{
data.recipient='other';
}
else
{
data.recipient='self';
}
user.user.messages.push(data);
if (user.user.last_msg == "" && user.user.id == $scope.chatUsers[$scope.selected].user.id) {
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
}
if (data.type == 2) {
user.user.last_msg = data.meta;
user.user.last_msg_type = 2;
} else if (data.type == 0) {
user.user.last_msg = data.text;
user.user.last_msg_type = 0;
}
user.user.total_messages_count += 1;
var curr_user_id= "user-"+user.user.id;
//if user selected and user msg recieved are differed=nt then increment otherwise no
if(curr_user_id != $(".all_users").parent().find('.active').data('id'))
{
user.user.total_unread_messages_count += 1;
$scope.overall_unread_messages_count += 1;
}
var audio = new Audio("#plugin_asset('WebsocketChatPlugin/audio/ping.mp3')");
audio.play();
//$("#chat-container").scrollTop($("#chat-container").find("> .img_main_div_padding").height());
});
socket.on("new_message_sent", function(data){
var user = $scope.findUserByID(data.to_user);
if(data.to_user==$scope.authUser)
{
data.recipient='other';
}
else
{
data.recipient='self';
}
user.user.messages.push(data);
if (user.user.last_msg == "" && user.user.id == $scope.chatUsers[$scope.selected].user.id) {
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
}
if (data.type == 2) {
user.user.last_msg = data.meta;
user.user.last_msg_type = 2;
} else if (data.type == 0) {
user.user.last_msg = data.text;
user.user.last_msg_type = 0;
}
// user.user.total_messages_count += 1;
// user.user.total_unread_messages_count += 1;
//$("#chat-container").scrollTop($("#chat-container").find("> .img_main_div_padding").height());
});
/*end of socket operations */
/* user online offline status */
socket.on('user_online', function(data){
var user = $scope.findUserByID(data.user_id);
if (user) {
user.online = 1;
}
});
socket.on('user_offline', function(data){
var user = $scope.findUserByID(data.user_id);
if (user) {
user.online = 0;
}
});
/* end user online offline status */
//event listening to contact delete
socket.on('contact_deleted', function(data){
$scope.getChatUsers();
});
$scope.isTypingUser=0;
/* typing stop and start notification */
socket.on('typing', function(data){
var user = $scope.findUserByID(data.from_user);
if (user) {
user.user.isTyping = true;
console.log(user.user.name + " is typing..");
//$scope.isTypingUser=1;
$('#typing_'+user.user.id).show();
}
});
socket.on('typing_stop', function(data){
var user = $scope.findUserByID(data.from_user);
if (user) {
user.user.isTyping = false;
console.log(user.user.name + " is stopped typing..");
$('#typing_'+user.user.id).hide();
}
});
$scope.typing = function(){
if (!$scope.type) {
$scope.type = true;
socket.emit('typing', {from_user: auth_user_id_chat, to_user:$scope.chatUsers[$scope.selected].user.id });
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= 2000 && $scope.type) {
socket.emit('typing_stop', {from_user: auth_user_id_chat, to_user:$scope.chatUsers[$scope.selected].user.id });
$scope.type = false;
}
}, 2000);
}
/* end typing stop and start notification */
/* new user contacted */
socket.on("new_user_contacted", function(data){
var user = $scope.findUserByID(data.user_id);
/* if user is already in list then remove*/
if (user) {
if(!$scope.total_contacts_count)
{
$scope.chatUsers=[];
}
else
{
var index = $scope.chatUsers.indexOf(user);
$scope.chatUsers.splice(index, 1);
}
}
//push object again retriving ajax call
$http.post(chat_user, {user_id:data.user_id})
.then(function(response){
if (response.data.status == 'success') {
//$scope.chatUsers.push(response.data.chat_user);
var temp = [];
temp.push(response.data.chat_user);
$scope.chatUsers = $.merge(temp, $scope.chatUsers);
$scope.chatUsers = _.uniq($scope.chatUsers, function(a) { return a.contact_id; });
}
}
,function(response){});
});
/* end new user contacted */
$scope.findUserByID = function(user_id){
if ($scope.chatUsers.length < 1)
return null;
return $scope.chatUsers.find(function(item){
if(item.user.id == user_id) return true;
});
}
$scope.mapUserWithSocket = function() {
$http.post(map_user_socket,
{socket_id:$scope.socket_id}).then(function(response){
if (response.data.status == 'success') {
socket.emit('user_socket_mapped', {user_id:auth_user_id_chat})
console.log('you are connected');
}
}, function(){});
}
function swapElement(array, indexA, indexB) {
var tmp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = tmp;
return array;
}
$scope.chatUsers = [];
$scope.chat_users_count = 0;
$scope.total_contacts_count = 0;
$scope.last_contact_id = 0;
$scope.authUser = auth_user_id_chat;
$scope.overall_unread_messages_count = 0;
/* this method gets chat users */
$scope.getChatUsers = function(){
$http.get(
chat_users,
{last_contact_id:$scope.last_contact_id}
).then(function(res){
if(res.data.status == "success") {
$scope.total_contacts_count = res.data.total_contacts_count;
$scope.chatUsers = res.data.chat_users;
if($scope.contact_id_already_contacted)
{
_.each($scope.chatUsers, function(listItem,index){
if(listItem.contact_id == $scope.contact_id_already_contacted)
$scope.indexToBeSelected = index;
})
$scope.chatUsers = swapElement($scope.chatUsers, $scope.indexToBeSelected,0);
}
$scope.chat_users_count = $scope.chatUsers.length;
if ($scope.total_contacts_count == 0 || $scope.chat_users_count == 0) {
$scope.last_contact_id = 0;
} else {
$scope.last_contact_id = $scope.chatUsers[$scope.chat_users_count-1].contact_id;
}
if ($scope.total_contacts_count != 0 && $scope.load_chat_data_first == true) {
$scope.loadChatDataFirst();
$('#fourth_div').hide();
}
else
{
$('#fourth_div').show();
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").hide();
}
$scope.overall_unread_messages_count = res.data.overall_unread_messages_count;
}
}, function(res){});
}
/* this method retrives message of a particular user */
$scope.getMessages = function(user){
$http.post(
msgs_chat,
{user_id:user.user.id, last_message_id:$scope.last_message_id}
).then(function(res){
if (res.data.status == 'success') {
var temp = [];
$.merge(temp, res.data.messages);
_.each(temp,function(item,index){
if(item.to_user==$scope.authUser)
{
temp[index].recipient='other';
}
else
{
temp[index].recipient='self';
}
})
user.user.messages = $.merge(temp, user.user.messages);
}
}, function(res){});
}
/* this method is used to send message */
$scope.submitMessage = function(){
console.log('$scope.messageInput',$scope.messageInput);
var to_send_user = $scope.chatUsers[$scope.selected];
if($scope.messageInput.indexOf(':')==0)
$scope.messageInput = emojione.shortnameToUnicode($scope.messageInput)
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 0,
message_text : $scope.messageInput
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
$scope.messageInput='';
}
/* submit messege with media
/* this method is used to send message */
$scope.submitMessageWithMedia = function(image_name){
var to_send_user = $scope.chatUsers[$scope.selected];
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 2,
message_text : image_name
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
}
$scope.submitMessageFirstTime = function(){
var to_send_user = $scope.chatUsers[$scope.selected];
if($scope.messageInput.indexOf(':')==0)
$scope.messageInput = emojione.shortnameToUnicode($scope.messageInput)
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 0,
message_text : $scope.messageInput
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
$scope.loadChatData(to_send_user, $scope.selected);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
$scope.messageInput='';
}
$scope.loadOnline =function() {
var counter=0;
$scope.onlineSelectedUsers = _.filter($scope.chatUsers, function (item,index) {
if(item.online && counter==0){
$scope.chatUsers[index].user.already_clicked= 0;
$scope.loadChatData($scope.chatUsers[index],index);
counter++;
}
return item.online;
});
var onlineUsers_count = $scope.onlineSelectedUsers.length;
if(onlineUsers_count == 0)
{
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
}
}
$scope.loadOnline_mobile =function() {
$scope.onlineSelectedUsers = _.filter($scope.chatUsers, function (item) { return item.online; });
if($scope.total_contacts_count)
{
if ($scope.onlineSelectedUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
$scope.loadChatData($scope.onlineSelectedUsers[0],0);
}
}
$scope.loadMatched = function() {
var counter=0;
$scope.matchedUsers = _.filter($scope.chatUsers, function (item,index) {
if(item.matched && counter==0){
$scope.chatUsers[index].user.already_clicked= 0;
$scope.loadChatData($scope.chatUsers[index],index);
counter++;
}
return item.matched;
});
var matchedUsers_count = $scope.matchedUsers.length;
if(matchedUsers_count == 0)
{
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
}
}
$scope.loadAll =function() {
if($scope.total_contacts_count)
{
if ($scope.chatUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
$scope.loadChatData($scope.chatUsers[0],0);
}
}
$scope.loadAll_mobile =function() {
if ($scope.chatUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
if($scope.total_contacts_count)
$scope.loadChatData($scope.chatUsers[0],0);
}
$scope.selected = 0;
$scope.loadChatData = function(user,index) {
//$scope.selected = index;
//index = $scope.chatUsers.indexOf(user);
if(user !=undefined)
{
$scope.current_to_user_id=user.user.id;
if(!$scope.total_contacts_count)
{
$http.post(add_to_contacts, {user_id:user.user.id})
.then(function(response){
if (response.data.status == 'success') {
$scope.getChatUsers();
}
}
,function(response){});
}
//hide the button
$('#load_more').show();
$scope.userChatDetail = user;
$scope.selected = index;
if (user.user.last_msg) {
$scope.last_message_id = 0;
if (user.user.messages.length > 0) {
$scope.last_message_id = user.user.messages[0].id;
}
if(!user.already_clicked) {
$('.loaderChatData').fadeIn();
$scope.getMessages(user);
user.already_clicked = 1;
//clear unread mesg count
user.user.total_unread_messages_count= 0;
//call function to make unread status for this user once i click on unread mesges
//pending
$http.post(
mark_read ,
{user_id:user.user.id}
).then(function(res){
console.log(res);
$('.loaderChatData').fadeOut();
});
}
if(user.already_clicked)
{
//clear unread mesg count
user.user.total_unread_messages_count= 0;
//$scope.getMessages(user);
}
// $scope.last_msg = user.user.last_msg;
// $scope.last_msg_type = user.user.last_msg_type;
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
if($scope.mobile)
{
$('.mobile_users').hide();
}
}
else
{
$('#third_img_div').hide();
$('#first_img_div').show();
$("#no-users-div").hide();
$("#fourth_div").hide();
if($scope.mobile)
{
$('.mobile_users').hide();
}
}
}
}
$scope.loadMoreChatData =function(user,index,last_msg_id)
{
$scope.userChatDetail = user;
$scope.selected = index;
if (user.user.last_msg) {
$scope.last_message_id = 0;
if (user.user.messages.length > 0) {
$scope.last_message_id = last_msg_id;
}
$scope.getMessages(user);
// $scope.last_msg = user.user.last_msg;
// $scope.last_msg_type = user.user.last_msg_type;
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
}
else
{
$('#third_img_div').hide();
$('#first_img_div').show();
$("#no-users-div").hide();
}
}
$scope.loadChatDataFirst = function() {
$scope.loadChatData($scope.chatUsers[0], 0);
}
});
/* this is socket factory */
App.factory('socket', function ($rootScope) {
var socket = io(websocket_domain+":"+server_port);
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
/* end of socket factory */

JavaScript Returns from Functions. Functions calling functions

I am trying to get a better understanding on javacsript. And I am not sure why this code is not working. I am trying to create functions that will call another function. And return the results of the called function.
When I call the below, I get fully logged in and presented with the screen I desire. But jsDidLogin Always returns undefined. Is there a better way to implement my methods?
var jsDidLogin = beginLogin()
console.log(jsDidLogin)
function waitUntilElementFound(element, time, callFunction) //Wait for the element to be found on the page
{
if (document.querySelector(element) != null) {
return callFunction();
}
else {
if (!checkForFailedLogin()) {
setTimeout(function () {
waitUntilElementFound(element, time, callFunction);
}, time);
}
else {
return false;
}
}
}
function checkForFailedLogin() {
if (document.querySelector("div[class='modal-body ng-scope'] h1") != null) {
if(document.querySelector("div[class='modal-body ng-scope'] h1").innerHTML == "Login Error")
{
return true;
}
}
else {
return false;
}
}
function initialTabSelect() //Load the bank page once login is completed
{
document.querySelectorAll("li[class='Tab'] a")[0].click();
return "Fully Logged In";
}
function initialDoNotAsk() {
document.querySelectorAll("a[ng-click='modalCancel()']")[0].click();
return waitUntilElementFound("li[class='Tab'] a", 1000, initialTabSelect);
}
function initialLogin() {
var accountName = document.getElementById("username");
var accountPassword = document.getElementById("password");
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
accountName.value = "USERNAME";
accountPassword.value = "PASSWORD";
accountName.dispatchEvent(evt);
accountPassword.dispatchEvent(evt);
document.querySelectorAll("form[name='loginForm'] button.icon-login")[0].click();
return waitUntilElementFound("a[ng-click='modalCancel()']", 2000, initialDoNotAsk);
}
function beginLogin() {
return waitUntilElementFound("form[name='loginForm'] button.icon-login", 1000, initialLogin);
}
Changing to this alerts me when Fully Logged in, but if I change it to return status. I still get no returns.
My head is starting to hurt :(
function waitUntilElementFound(element, time, callFunction, callBack) //Wait for the element to be found on the page
{
if (document.querySelector(element) != null) {
callBack(callFunction());
}
else {
if (!checkForFailedLogin()) {
setTimeout(function () {
callBack(waitUntilElementFound(element, time, callFunction, function(status){alert(status);}));
}, time);
}
else {
return false;
}
}
}
function checkForFailedLogin() {
if (document.querySelector("div[class='modal-body ng-scope'] h1") != null) {
if(document.querySelector("div[class='modal-body ng-scope'] h1").innerHTML == "Login Error")
{
return true;
}
}
else {
return false;
}
}
function initialTabSelect() //Load the bank page once login is completed
{
document.querySelectorAll("li[class='Tab'] a")[0].click();
return "Fully Logged In";
}
function initialDoNotAsk() {
document.querySelectorAll("a[ng-click='modalCancel()']")[0].click();
return waitUntilElementFound("li[class='Tab'] a", 1000, initialTabSelect, function(status){alert(status)};);
}
function initialLogin() {
var accountName = document.getElementById("username");
var accountPassword = document.getElementById("password");
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
accountName.value = "USERNAME";
accountPassword.value = "PASSWORD";
accountName.dispatchEvent(evt);
accountPassword.dispatchEvent(evt);
document.querySelectorAll("form[name='loginForm'] button.icon-login")[0].click();
return waitUntilElementFound("a[ng-click='modalCancel()']", 2000, initialDoNotAsk, function(status){alert(status)};);
}
function beginLogin() {
return waitUntilElementFound("form[name='loginForm'] button.icon-login", 1000, initialLogin, function(status){alert(status)};);
}

How to prevent two JavaScript files from executing simultaneously

I have two JavaScript files. One is running validation, and other have ajax plugin that sends form after validation.
When I attached these files in the header section, then they simultaneously run, but if I attach these two files in the body, then validation runs as it should but ajax call not working.
There is no any error on the console as well.
..
What you people suggests?
AjaxCall.js
$(document).ready(function() {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: 'quoteProcess.php', // override for form's 'action' attribute
type: 'post', // 'get' or 'post', override for form's 'method' attribute
clearForm: true // clear all form fields after successful submit
};
// bind 'myForm' and provide a simple callback function
$('#testform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.modal').show();
return true;
}
function showResponse(responseText, statusText, xhr, $form) {
$('.modal').hide();
alert( '\n\nYour Quote has been Recieved ! \n' + responseText +
'\n');
window.location.replace("http://localhost/lamozine/quote.php");
}
validation.js
(function($){
var functions = {
reset: resetValidation
};
var settings;
var _reqForm;
var _indicatorTemplate = '<span class="error-indicator" role="alert" aria-live="assertive" aria-hidden="true"></span>';
var _summaryTemplate = '<div id="errorSummary" class="alert alert-danger" role="alert" aria-live="assertive" tabindex="-1"><p>{0}</p></div>';
var _validationTypes = {
required: {msg: ' is required' },
tel: {msg: ' is not a valid phone number' },
email: {msg: ' is not a valid email address' },
date: {msg: ' is not a valid date'},
number: {msg: ' is not a valid number'}
};
$.fn.attrvalidate = function() {
if (!this.is('form')) {
return this;
}
if (typeof arguments[0] === 'string') {
var property = arguments[1];
var newArgs = Array.prototype.slice.call(arguments);
newArgs.splice(0, 1);
functions[arguments[0]].apply(this, newArgs);
} else {
setupFormValidation.apply(this, arguments);
}
return this;
};
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function setupFormValidation(options){
settings = $.extend({
showFieldIndicator: true,
showErrorSummary: true,
errorSummaryMsg: 'Please fix the following issues before continuing:',
validateTel: true,
telRegex: /^\+*[\d-()]{7,20}$/,
validateEmail: true,
emailRegex: /^(\S+#\S+)*$/,
validateDate: true,
validateNumber: true
}, options);
_reqForm = this;
initialiseValidation();
$(_reqForm).bind('submit', handleSubmit);
}
function initialiseValidation(){
var _groupsInitialised = [];
$(_reqForm).find('input, select[required], textarea[required]').each(function(){
if (isRadioGroup($(this)) && $(this).is('[required]')) {
var groupName = $(this).attr('name');
if ($.inArray(groupName, _groupsInitialised) === -1) {
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
$(this).parents('fieldset').first().append($(_indicatorTemplate));
}
$(_reqForm).find('input[name="' + $(this).attr('name') + '"]').each(function(){
$(this).change(function(){
handleFieldChanged($(this));
});
});
_groupsInitialised.push(groupName);
}
} else {
if ($(this).is('[required]') ||
(settings.validateTel && $(this).is('input[type="tel"]')) ||
(settings.validateEmail && $(this).is('input[type="email"]')) ||
(settings.validateDate && $(this).is('input[type="date"]')) ||
(settings.validateNumber && $(this).is('input[type="number"]'))){
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
if (($(this).is('input[type="radio"]') || $(this).is('input[type="checkbox"]')) && $(this).next('label').length > 0) {
$(this).next('label').after($(_indicatorTemplate));
} else {
$(this).after($(_indicatorTemplate));
}
}
$(this).change(function(){
handleFieldChanged($(this));
});
}
}
});
}
function handleFieldChanged(elem){
var validationResult = validateField(elem);
if (validationResult.isValid) {
clearFieldError(elem);
} else {
var fieldMsg = getFieldMessage(elem, validationResult.type);
showFieldError(elem, fieldMsg);
}
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}
function validateField(elem){
if (!elem.is(':visible') || elem.parents('[aria-hidden="true"]').length > 0){
return { isValid: true };
}
if (elem.is('input[type="radio"]')) {
if (elem.is('[required]')){
if (isRadioGroup(elem)) {
return { isValid: ($(_reqForm).find('input[name="' + elem.attr('name') + '"]:checked').length > 0), type: _validationTypes.required };
} else {
return { isValid: elem.is(':checked'), type: _validationTypes.required };
}
} else {
return { isValid: true };
}
} else if (elem.is('input[type="checkbox"]')) {
return { isValid: (!elem.is('[required]') || elem.is(':checked')), type: _validationTypes.required };
} else {
if (elem.is('[required]') && (elem.val() === '')) {
return { isValid: false, type: _validationTypes.required };
} else if (settings.validateTel && elem.is('input[type="tel"]')) {
return { isValid: settings.telRegex.test(elem.val().replace(/ /g, '')), type: _validationTypes.tel };
} else if (settings.validateEmail && elem.is('input[type="email"]')) {
return { isValid: settings.emailRegex.test(elem.val().trim()), type: _validationTypes.email };
} else if (settings.validateDate && elem.is('input[type="date"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(Date.parse(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(Date.parse(elem.prop('max'))) && Date.parse(elem.val()) > Date.parse(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(Date.parse(elem.prop('min'))) && Date.parse(elem.val()) < Date.parse(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.date };
} else if (settings.validateNumber && elem.is('input[type="number"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(parseFloat(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(parseFloat(elem.prop('max'))) && parseFloat(elem.val()) > parseFloat(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(parseFloat(elem.prop('min'))) && parseFloat(elem.val()) < parseFloat(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.number };
} else {
return { isValid: true };
}
}
}
function setFieldName(elem){
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
return;
}
var elemName;
var forLabel = $(_reqForm).find('label[for="' + elem.attr('id') + '"]');
if (forLabel.length > 0 && $(forLabel[0]).text() !== '') {
elemName = $(forLabel[0]).text();
} else {
elemName = elem.attr('name');
}
elem.data('error-name', elemName);
}
function getFieldMessage(elem, resultType){
var elemMsg;
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
elemMsg = elem.data('error-msg');
} else {
elemMsg = elem.data('error-name') + resultType.msg;
}
return elemMsg;
}
function showFieldError(elem, fieldMsg){
if (isRadioGroup(elem)) {
elem.parents('fieldset').first().addClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
} else {
elem.addClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
}
}
function clearFieldError(elem){
if (isRadioGroup(elem)) {
elem.parents('fieldset').removeClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().attr('aria-hidden', true);
}
var firstInGroup = $(_reqForm).find('input[name="' + elem.attr('name') + '"]').first();
var summaryItem = $('#errorSummary li a[data-field="' + firstInGroup.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
} else {
elem.removeClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().attr('aria-hidden', true);
}
var summaryItem = $('#errorSummary li a[data-field="' + elem.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
}
}
function showErrorSummary(errorMsgList){
var errorSummary = $(_summaryTemplate.replace('{0}', settings.errorSummaryMsg));
var errorList = $('<ul></ul>');
for (var i=0; i < errorMsgList.length; i++) {
var errorLink = $('' + errorMsgList[i].msg + '');
errorLink.click(function(){ jumpToElem($(this).data('field')); return false; });
var errorItm = $('<li></li>');
errorItm.append(errorLink);
errorList.append(errorItm);
}
errorSummary.append(errorList).prependTo($(_reqForm));
errorSummary.focus();
}
function isRadioGroup(elem){
return (elem.is('input[type="radio"]') && typeof(elem.attr('name')) !== 'undefined' && elem.attr('name') !== '');
}
function jumpToElem(fieldId){
$(_reqForm).find('#' + fieldId).focus();
}
}(jQuery));
I am not clear with your question very well but if you want to load one script file after loading an another script file. You can simple load using $.when() and $.getScript() jquery functions like this.
$.getScript() will load javascript file asynchronously and .done() call back of $.when() method will continue after the loading script done.
This is a very simple sample.
<html>
<head>
<script src="/jquery.min.js"></script>
</head>
<body>
<script>
$.when(
$.getScript("/mypath/validation.js")
).done(function(){
$.getScript("/mypath/AjaxCall.js")
});
</script>
</body>
Hope it might help.

How to make touch event in one HTML file effect things in a separate HTML file?

I'm not sure if this is possible, here is what I mean:
I have a touch event to hide/show an hourly forecast, but now I need to make the touch event on a separate HTML file, so when I tap the touch event on one html file the forecast (displayed in a separate html file) will disappear, can this be done?
Here is my js file for all the touch events:
// UniAW6.4LS By Ian Nicoll and Dacal
var forecastdisplay = true;
var hourlyforecastdisplay = true;
var slideshow = false;
var optiondisplay = false;
var weatherdisplay = true;
var weatherBGdisplay = true;
var clockdisplay = true;
var timedwalls = false;
var disabletouch = false;
var windeffectdisplay = true;
var prev_wind_effects = wind_effects; // TO REVERT BACK...
var touchdownX;
var touchupX;
var touchX;
var stateX = 0;
var stateY = 0;
if (ChangeClick == false) { var touchmode = "touchend"; } else { var touchmode = "click"; }
function StartTouch() {
if (ChangeClick == false) {
document.getElementById("HourlyTouchLayer").addEventListener("touchstart", touchStart, false); // FOR THE HOURLY FORECAST
document.getElementById("HourlyTouchLayer").addEventListener("touchmove", touchMove, false); // FOR THE HOURLY FORECAST
} else {
document.getElementById("HourlyTouchLayer").addEventListener("mousedown", mouseDown, false); // FOR THE HOURLY FORECAST
document.getElementById("HourlyTouchLayer").addEventListener("mouseup", mouseUp, false); // FOR THE HOURLY FORECAST
}
document.getElementById("TouchLayer").addEventListener(touchmode, touchEnd, false); // FOR THE FORECAST
document.getElementById("TouchLayer2").addEventListener(touchmode, touchEnd2, false); // FOR THE OPTIONS
}
function touchEnd() {
if (forecastdisplay == false) {
document.getElementById('TouchForecast').className = "forecastMoveUp";
forecastdisplay = true;
} else {
document.getElementById('TouchForecast').className = "forecastMoveDown";
forecastdisplay = false;
}
if (updateFileTimer != "") { createOptionsCookie(); }
}
function touchEnd2(event) {
event.preventDefault();
if (optiondisplay == false) {
document.getElementById("optionContainer").style.zIndex= "1000";
document.getElementById("optionContainer").className = "fade-in-option";
StartButtons();
optiondisplay = true;
} else {
document.getElementById("optionContainer").style.zIndex= "800";
document.getElementById("optionContainer").className = "fade-out-option";
StopButtons();
optiondisplay = false;
}
}
function touchStart(event) {
event.preventDefault();
touchdownX = event.targetTouches[0].pageX;
}
function touchMove(event) {
event.preventDefault();
touchupX = event.targetTouches[0].pageX;
touchX = touchupX - touchdownX;
if (touchX != 0) { MoveElementX(); }
}
function mouseDown(event) {
event.preventDefault();
touchdownX = event.pageX;
}
function mouseUp(event) {
event.preventDefault();
touchupX = event.pageX;
touchX = touchupX - touchdownX;
if (touchX != 0) { MoveElementX(); }
}
function MoveElementX() {
if (hourlyforecastdisplay == true) {
switch (stateX) {
case 0 :
if ( touchX < 0 ) {
document.getElementById("hourlyforecast").className = "forecastTranslateLeft";
stateX++;
}
break;
case 1 :
if ( touchX > 0 ) {
document.getElementById("hourlyforecast").className = "forecastTranslateRight";
stateX--;
}
break;
}
}
}
function StartButtons() {
document.getElementById("refresh").addEventListener(touchmode, touchRefresh, false);
document.getElementById("timedwall").addEventListener(touchmode, touchTimewall, false);
document.getElementById("slideshow").addEventListener(touchmode, touchSlideShow, false);
document.getElementById("hideweatherInfo").addEventListener(touchmode, touchHideWeather, false);
document.getElementById("hideweatherBG").addEventListener(touchmode, touchHideWeatherBG, false);
document.getElementById("hideclock").addEventListener(touchmode, touchHideClock, false);
document.getElementById("disableforcasttouch").addEventListener(touchmode, touchDisableForecast, false);
document.getElementById("windeffect").addEventListener(touchmode, touchWindeffect, false);
document.getElementById("disablehourlyforcast").addEventListener(touchmode, touchHideHourlyForecast, false);
document.getElementById("refresh").innerHTML = "Reload (for a fresh start)";
document.getElementById("timedwall").innerHTML = "Launch Timed Walls";
document.getElementById("slideshow").innerHTML = "Launch the Slideshow";
document.getElementById("hideweatherInfo").innerHTML = "Hide all weather information";
document.getElementById("hideweatherBG").innerHTML = "Hide all overlay";
document.getElementById("hideclock").innerHTML = "Hide the clock";
document.getElementById("disableforcasttouch").innerHTML = "Disable forecast touch";
document.getElementById("windeffect").innerHTML = "Disable Wind Effect";
document.getElementById("disablehourlyforcast").innerHTML = "Hide Hourly Forecast";
}
function StopButtons() {
document.getElementById("refresh").removeEventListener(touchmode, touchRefresh, false);
document.getElementById("timedwall").removeEventListener(touchmode, touchTimewall, false);
document.getElementById("slideshow").removeEventListener(touchmode, touchSlideShow, false);
document.getElementById("hideweatherInfo").removeEventListener(touchmode, touchHideWeather, false);
document.getElementById("hideweatherBG").removeEventListener(touchmode, touchHideWeatherBG, false);
document.getElementById("hideclock").removeEventListener(touchmode, touchHideClock, false);
document.getElementById("disableforcasttouch").removeEventListener(touchmode, touchDisableForecast, false);
document.getElementById("windeffect").removeEventListener(touchmode, touchWindeffect, false);
document.getElementById("disablehourlyforcast").removeEventListener(touchmode, touchHideHourlyForecast, false);
}
function touchRefresh() {
event.preventDefault();
$.removeCookie('optionsCookie');
window.location.reload();
}
function touchTimewall() {
if (timedwalls == false) {
if (slideshow == true) { touchSlideShow(); }
timedwalls = true;
Wallpaper_options = 'timedwalls';
document.getElementById("backgroundContainer").className = "fade-out-wall";
document.getElementById("timedwall").className = "TextColorGreen";
} else {
timedwalls = false;
wpidx = "-1";
WPfade_inTW.className='fade-out-wall';
WPfade_outTW.className='fade-out-wall';
document.getElementById("backgroundContainer").className = "fade-in-wall";
document.getElementById("timedwall").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchSlideShow() {
if (slideshow == false) {
if (timedwalls == true) { touchTimewall(); } // STOP THE TIMED WALL
widgetStart();
slideshow = true;
Wallpaper_options = 'slideshow';
document.getElementById("slideshow").className = "TextColorGreen";
if (filename != "") {
clearInterval(meteorTimer);
delelement("astronautContainer");
delelement("fogContainer");
delelement("starContainer");
delelement("meteorContainer");
delelement("frameContainer");
delelement("cloudContainer");
delelement("dropContainer");
delelement("circleContainer");
delelement("wiperContainer");
delelement("starsBGContainer");
delelement("windContainer");
delelement("windmillContainer");
delelement("big_balloonContainer");
delelement("small_balloonContainer");
delelement("birdsContainer");
delelement("frostContainer");
if (Show_wind_effects == true) {
removejscssfile("Weather/"+iPhoneType, wind_effects+"_effects", "css");
removejscssfile("Weather/"+iPhoneType, wind_effects+"_effects", "js");
Show_wind_effects = false;
}
if (Show_frost == true) {
removejscssfile("Weather/" + iPhoneType, "frost_effect", "css");
removejscssfile("Weather/" + iPhoneType, "frost_effect", "js");
Show_frost = false;
}
removejscssfile("Weather/"+iPhoneType, filename, "css");
removejscssfile("Weather/"+iPhoneType, filename, "js");
}
document.getElementById("sun_moonContainer").className = "fade-out-wall";
document.getElementById("backgroundContainer").className = "fade-out-wall";
} else {
widgetStop();
slideshow = false;
if (filename != "") {
loadjscssfile ("Weather/"+iPhoneType, filename, "css");
loadjscssfile ("Weather/"+iPhoneType, filename, "js");
if (Start_wind_effects == true) {
loadjscssfile ("Weather/"+iPhoneType, wind_effects+"_effects", "css");
loadjscssfile ("Weather/"+iPhoneType,wind_effects+"_effects", "js");
Show_wind_effects = true;
}
if (Start_frost == true) {
loadjscssfile("Weather/" + iPhoneType, "frost_effect", "css");
loadjscssfile("Weather/" + iPhoneType, "frost_effect", "js");
Show_frost = true;
}
}
document.getElementById("sun_moonContainer").className = "fade-in-wall";
document.getElementById("backgroundContainer").className = "fade-in-wall";
document.getElementById("slideshow").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchHideWeather() {
if (weatherdisplay == true) {
document.getElementById("WeatherInfo").className = "fade-out-wall";
document.getElementById("forecastInfo").className = "fade-out-wall";
document.getElementById("hourlyforecast").className = "fade-out-wall";
weatherdisplay = false;
document.getElementById("hideweatherInfo").className = "TextColorGreen";
} else {
document.getElementById("WeatherInfo").className = "fade-in-wall";
document.getElementById("forecastInfo").className = "fade-in-wall";
document.getElementById("hourlyforecast").className = "fade-in-wall";
weatherdisplay = true;
document.getElementById("hideweatherInfo").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchHideClock() {
if (clockdisplay == true) {
document.getElementById("clockContainer").className = "fade-out-wall";
clockdisplay = false;
document.getElementById("hideclock").className = "TextColorGreen";
} else {
document.getElementById("clockContainer").className = "fade-in-wall";
clockdisplay = true;
document.getElementById("hideclock").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchHideWeatherBG() {
if (weatherBGdisplay == true) {
document.getElementById("forecastbg").style.display = 'none';
document.getElementById("hourlyforecastbg").style.display = 'none';
document.getElementById("WeatherInfoBG").className = "fade-out-wall";
weatherBGdisplay = false;
document.getElementById("hideweatherBG").className = "TextColorGreen";
} else {
document.getElementById("forecastbg").style.display = 'block';
document.getElementById("hourlyforecastbg").style.display = 'block';
document.getElementById("WeatherInfoBG").className = "fade-in-wall";
weatherBGdisplay = true;
document.getElementById("hideweatherBG").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchDisableForecast() {
if (disabletouch == true) {
document.getElementById("TouchLayer").addEventListener(touchmode, touchEnd, false);
disabletouch = false;
document.getElementById("disableforcasttouch").className = "TextColorWhite";
} else {
document.getElementById("TouchLayer").removeEventListener(touchmode, touchEnd, false);
disabletouch = true;
document.getElementById("disableforcasttouch").className = "TextColorGreen";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchWindeffect() {
if (windeffectdisplay == true) {
prev_wind_effects = wind_effects;
wind_effects = "none";
Start_wind_effects = false;
windeffectdisplay = false;
document.getElementById("windeffect").className = "TextColorGreen";
if (Show_wind_effects == true) {
delelement("windContainer");
delelement("windmillContainer");
removejscssfile("Weather/"+iPhoneType, wind_effects+"_effects", "css");
removejscssfile("Weather/"+iPhoneType, wind_effects+"_effects", "js");
Show_wind_effects = false;
}
} else {
wind_effects = prev_wind_effects;
if ((filename != "") && (slideshow == false) && (Show_wind_effects == false)) {
if ((Math.round(obj.windspeed) >= Strong_Wind) && (filename != "windy") && (wind_effects != "none")) { Start_wind_effects = true; } else { Start_wind_effects = false; }
if (Start_wind_effects == true) {
loadjscssfile ("Weather/"+iPhoneType, wind_effects+"_effects", "css");
loadjscssfile ("Weather/"+iPhoneType, wind_effects+"_effects", "js");
Show_wind_effects = true;
}
}
windeffectdisplay = true;
document.getElementById("windeffect").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function touchHideHourlyForecast() {
if (hourlyforecastdisplay == true) {
document.getElementById("hourlyforecast").className = "fade-out-wall";
document.getElementById("hourlyforecastbg").style.display = 'none';
hourlyforecastdisplay = false;
document.getElementById("disablehourlyforcast").className = "TextColorGreen";
} else {
document.getElementById("hourlyforecast").className = "fade-in-wall";
document.getElementById("hourlyforecastbg").style.display = 'block';
hourlyforecastdisplay = true;
document.getElementById("disablehourlyforcast").className = "TextColorWhite";
}
if (optiondisplay == true) { createOptionsCookie(); } // SAVE THE CONFIGURATION
}
function createOptionsCookie() {
var options = {};
options.slideshow = slideshow;
options.clockdisplay = clockdisplay;
options.weatherdisplay = weatherdisplay;
options.timedwalls = timedwalls;
options.weatherBGdisplay = weatherBGdisplay;
options.disabletouch = disabletouch;
options.forecastdisplay = forecastdisplay;
options.windeffectdisplay = windeffectdisplay;
options.hourlyforecastdisplay = hourlyforecastdisplay;
var optionsTmp = JSON.stringify(options);
$.cookie('optionsCookie', optionsTmp, {expires: 365});
}
Does the page receiving the touch event have a reference (or can get a reference) to the forecast page? For example, is the forecast page in an iframe inside the original page?
If so, you could use postMessage() to communicate from the original page to the forecast page.
OTOH, if the forecast page is inside an iframe, and all you want to do is remove the forecast entirely, then all you really need to do is have the original page remove the iframe from the DOM.
I'd be happy to talk about any approach in more detail, but first how about providing some more information about these pages and how they are loaded?
Without developing a data-driven backend (PHP, Node, RoR - to name the most popular), your best bet is probably working with LocalStorage.
var foo = localStorage.getItem("bar");
// ...
localStorage.setItem("bar", foo);
When handling the touch event, you could set a variable with localStorage, and then in the other HTML page, look for a corresponding item and act on the value (or lack thereof) of that value.
You may also want to hook into the localStorage change event - just "storage":
HTML5 / JS storage event handler
document.addEventListener('storage', storageEventHandler, false);
var storageEventHandler = function(event){
//do something
}

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

Categories