I got a function for removing elements from the site. When i click the "ok" button the console tells me "removeElements is not defined"...?! But in my opinion everything is done right.
Here is the code:
function showPic(obj, yes)
{
var obj = (yes) ? obj : this;
if(!isTimeRunning)
{
isTimeRunning = true;
chronoId = setInterval(function() { chronometro() }, 1000);
pointers[game] = chronoId;
}
if(!waitASecond)
{
if(!imagesInGame.isInArray(obj))
{
return;
}
if(!clicks.length)
{
clicks[0] = obj;
if(!openedImages.isInArray(obj))
{
notOpenedImages.deleteElementByValue(obj.divNum, 'divNum');
}
obj.firstChild.style.display = 'none';
}
else
{
if(clicks[0].divNum == obj.divNum)
return;
clicks[1] = obj;
if(!openedImages.isInArray(obj))
{
openedImages.push(obj);
notOpenedImages.deleteElementByValue(obj.divNum, 'divNum');
}
obj.firstChild.style.display = 'none';
waitASecond = true;
checkIdentity();
document.getElementById('numberOfTries' + game).value = allPlayers[player]['failures'];
}
}
}
function showPicOnclick()
{
if(humanPlayer)
showPic(this, true);
}
function checkIdentity()
{
if(clicks[0].imageNum == clicks[1].imageNum)
{
countPairs();
imagesInGame.deleteElementByValue(clicks[0].imageNum, 'imageNum');
openedImages.deleteElementByValue(clicks[0].imageNum, 'imageNum');
addElement('match_div_one_'+clicks[1].imageNum, "img");
addElement('match_div_two_'+clicks[1].imageNum, 'Inhalt1');
addElement('match_div_three_'+clicks[1].imageNum, 'Inhalt1');
addElement('match_div_button_'+clicks[1].imageNum, '<button onclick="removeElements()">OK</button>');
/*alert(messages[clicks[1].imageNum]); */
gotLastPair = player;
waitASecond = false;
clicks.clean();
checkForGameEnd();
}
else
{
allPlayers[player]['failures']++;
turnId = setTimeout(function() { hidePics() }, timeout);
}
}
function removeElement(divNum) {
var olddiv = document.getElementById(divNum);
olddiv.parentNode.removeChild(olddiv);
}
function removeElements() {
removeElement('match_div_one_'+clicks[1].imageNum);
removeElement('match_div_two_'+clicks[1].imageNum);
removeElement('match_div_three_'+clicks[1].imageNum);
removeElement('match_div_button_'+clicks[1].imageNum);
}
Related
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 */
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;
});
};
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
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
Currently having a problem where I have wanted to do a simple jQuery append to move a div into another div. In this case, when I type in the search box suggested results should appear underneath. However due to myself changing some of the code it no longer appears too the left so I did a simple jQuery append to make my life easier.
The problem is that when I make a simple search and the results box appears under the search box I use the console to excute the following line of code:
$('#QuickSearch').appendTo($('#searchheader'));
All works fine in the console. However when I put it in the search's javascript file, it does not execute that line of code. Below is the jQuery associated with the search:
var QuickSearch = {
minimum_length: 3,
search_delay: 125,
cache: new Object(),
init: function()
{
$('#search_query').bind("keydown", QuickSearch.on_keydown);
$('#search_query').bind("keyup", QuickSearch.on_keyup);
$('#search_query').bind("change", QuickSearch.on_change);
$('#search_query').blur(QuickSearch.on_blur);
$('#search_query').attr('autocomplete', 'off');
var scripts = document.getElementsByTagName('SCRIPT');
for(var i = 0; i < scripts.length; i++)
{
s = scripts[i];
if(s.src && s.src.indexOf('quicksearch.js') > -1)
{
QuickSearch.path = s.src.replace(/quicksearch\.js$/, '../');
break;
}
}
},
on_blur: function(event)
{
if(!QuickSearch.item_selected && !QuickSearch.over_all)
{
QuickSearch.hide_popup();
}
},
on_keydown: function(event)
{
if(event.keyCode == 13 && !event.altKey)
{
if(QuickSearch.selected)
{
try {
event.preventDefault();
event.stopPropagation();
} catch(e) { }
window.location = QuickSearch.selected.url;
return false;
}
else
{
QuickSearch.hide_popup();
}
}
else if(event.keyCode == 27)
{
if(document.getElementById('QuickSearch'))
{
try {
event.preventDefault();
event.stopPropagation();
} catch(e) { }
}
QuickSearch.hide_popup();
}
},
on_keyup: function(event)
{
if(QuickSearch.timeout)
{
clearTimeout(QuickSearch.timeout);
}
// Down key was pressed
if(event.keyCode == 40 && QuickSearch.results)
{
if(QuickSearch.selected && QuickSearch.results.length >= QuickSearch.selected.index+1)
{
QuickSearch.highlight_item(QuickSearch.selected.index+1, true);
}
if(!QuickSearch.selected && QuickSearch.results.length > 0)
{
QuickSearch.highlight_item(0, true);
}
try {
event.preventDefault();
event.stopPropagation();
} catch(e) { }
return false;
}
else if(event.keyCode == 38 && QuickSearch.results)
{
if(QuickSearch.selected && QuickSearch.selected.index > 0)
{
QuickSearch.highlight_item(QuickSearch.selected.index-1, true);
}
try {
event.preventDefault();
event.stopPropagation();
} catch(e) { }
}
else if(event.keyCode == 27)
{
QuickSearch.hide_popup();
}
else
{
if($('#search_query').val() == QuickSearch.last_query)
{
return false;
}
QuickSearch.selected = false;
if($('#search_query').val().replace(/^\s+|\s+$/g, '').length >= QuickSearch.minimum_length)
{
QuickSearch.last_query = $('#search_query').val().replace(/^\s+|\s+$/g, '');
if(QuickSearch.timeout)
{
window.clearTimeout(QuickSearch.timeout);
}
QuickSearch.timeout = window.setTimeout(QuickSearch.do_search, QuickSearch.search_delay);
}
else {
if(document.getElementById('QuickSearch'))
{
$('#QuickSearch').remove();
}
}
}
},
on_change: function(event)
{
return (QuickSearch.on_keydown(event) && QuickSearch.on_keyup(event));
},
do_search: function()
{
var cache_name = $('#search_query').val().length+$('#search_query').val();
if(QuickSearch.cache[cache_name])
{
QuickSearch.search_done(QuickSearch.cache[cache_name]);
}
else
{
$.ajax({
type: 'GET',
dataType: 'xml',
url: QuickSearch.path+'search.php?action=AjaxSearch&search_query='+encodeURIComponent($('#search_query').val()),
success: function(response) { QuickSearch.search_done(response); }
});
}
},
search_done: function(response)
{
// Cache results
var cache_name = $('#search_query').val().length+$('#search_query').val();
QuickSearch.cache[cache_name] = response;
if(document.getElementById('QuickSearch')) {
$('#QuickSearch').remove();
}
if ($('result', response).length > 0) {
var popup_container = document.createElement('TABLE');
popup_container.className = 'QuickSearch';
popup_container.id = 'QuickSearch';
popup_container.cellPadding = "0";
popup_container.cellSpacing = "0";
popup_container.border = "0";
var popup = document.createElement('TBODY');
popup_container.appendChild(popup);
var counter = 0;
$('result', response).each(
function()
{
var tr = $($(this).text());
var url = $('.QuickSearchResultName a', tr).attr('href');
var tmpCounter = counter;
$(tr).attr('id', 'QuickSearchResult' + tmpCounter);
$(tr).bind('mouseover', function() { QuickSearch.item_selected = true; QuickSearch.highlight_item(tmpCounter, false); });
$(tr).bind('mouseup', function() { window.location = url; });
$(tr).bind('mouseout', function() { QuickSearch.item_selected = false; QuickSearch.unhighlight_item(tmpCounter) });
$(popup).append(tr);
counter++;
}
);
// More results than we're showing?
var all_results_count = $('viewmoreurl', response).size();
if(all_results_count)
{
var tr = document.createElement('TR');
var td = document.createElement('TD');
tr.className = "QuickSearchAllResults";
tr.onmouseover = function() { QuickSearch.over_all = true; };
tr.onmouseout = function() { QuickSearch.over_all = false; };
td.colSpan = 2;
td.innerHTML = $('viewmoreurl', response).text();
tr.appendChild(td);
popup.appendChild(tr);
}
var clone = popup.cloneNode(true);
document.body.appendChild(clone);
clone.style.pp = "10px";
clone.style.left = "10px";
offset_height = clone.offsetHeight;
offset_width = clone.offsetWidth;
clone.parentNode.removeChild(clone);
var offset_top = offset_left = 0;
var element = document.getElementById('search_query');
if(typeof(QuickSearchAlignment) != 'undefined' && QuickSearchAlignment == 'left') {
offset_left = 0;
}
else {
offset_left += element.offsetWidth - $('#SearchForm').width();
}
offset_top = 87;
do
{
offset_top += element.offsetTop || 0;
offset_left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
popup_container.style.position = "fixed";
popup_container.style.top = offset_top + "px";
if(typeof(QuickSearchWidth) != 'undefined') {
popup_container.style.width = QuickSearchWidth;
}
else {
popup_container.style.width = document.getElementById('SearchForm').offsetWidth - 2 + "px";
}
if($('#QuickSearch'))
{
$('#QuickSearch').remove();
}
document.body.appendChild(popup_container);
popup_container.style.display = '';
}
else
{
if(document.getElementById('QuickSearch'))
{
$('#QuickSearch').remove();
}
}
},
hide_popup: function()
{
$('#QuickSearch').remove();
QuickSearch.selected = null;
},
highlight_item: function(index, keystroke)
{
element = $('#QuickSearchResult'+index);
if(keystroke == true)
{
if(QuickSearch.selected) QuickSearch.selected.className = 'QuickSearchResult';
QuickSearch.selected = document.getElementById('QuickSearchResult'+index);
}
element.addClass("QuickSearchHover");
},
unhighlight_item: function(index)
{
element = $('#QuickSearchResult'+index);
element.removeClass('QuickSearchHover');
}
};
$(document).ready(function()
{
QuickSearch.init();
});