How to set height and width of downloading image in javascript PHP - javascript

I am working with php and javascript,I have button "Download" and on button click
i am downloding "screenshot" (as html inside "wrapper div"),But i want to set "height" and "width" of
downloding screenshot,How can i do this ? Here is my code
<div id="wrapper">
<h3>Lorem Ipsum dummy text</h3>
</div>
<button onclick="generate()">Download</button>
<script>
(function(exports) {
function urlsToAbsolute(nodeList) {
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function(el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
var wrapper = document.getElementById('wrapper');
html2canvas(wrapper, {
onrendered: function(canvas) {
canvas.toBlob(function(blob) {
saveAs(blob, 'myScreenshot.png');
});
}
});
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function(e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
screenshotPage();
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
</script>

Related

Uncaught TypeError: Cannot read property 'show' of undefined on the float box

I am getting the following error on all browsers while opening the float box and then it cannot be closed. You need to refresh the page. There was no problem before. It was working fine. Now, I've been getting this error ever since I adapted the new design to the site. How can fix this problem? Thank you.
Uncaught TypeError: Cannot read property 'show' of undefined
// disabling/enabling
jQuery.fn.extend({
disable: function() {
this.each(function()
{
this.disabled = true;
if ( this.tagName != 'INPUT' && this.tagName != 'TEXTAREA' && this.tagName != 'SELECT' )
{
this.jQuery_disabled_clone =
jQuery(this)
.addClass('disabled')
.clone()
.removeAttr('id')
.get(0);
jQuery(this)
.hide()
.bind('unload', function(){
jQuery(this).enable();
})
.after(this.jQuery_disabled_clone);
}
});
return this;
},
enable: function()
{
this.each(function()
{
this.disabled = false;
if ( this.jQuery_disabled_clone )
{
jQuery(this.jQuery_disabled_clone).remove();
this.jQuery_disabled_clone = null;
jQuery(this)
.unbind('unload', function(){
jQuery(this).enable();
})
.removeClass('disabled')
.show();
}
});
return this;
}
});
function SK_Exception(message, code)
{
this.toString = function() {
return message;
}
this.getCode = function() {
return code;
}
}
function SK_drawError(err_msg, delay) {
SK_drawMessage(err_msg, 'error', delay);
}
function SK_drawMessage(msg_text, type, delay)
{
if (navigator.appName == 'Microsoft Internet Explorer' && (msg_text == "Virtual gift has been sent" || msg_text == "Hediyeniz başarıyla gönderildi.." || msg_text == "Virtual gift has not been sent" || msg_text == "Hediyeniz gönderilemedi.."))
alert(msg_text);
type = type || 'message';
delay = delay || (1000*10);
if (SK_drawMessage.in_process) {
if (msg_text) {
SK_drawMessage.queue.unshift([msg_text, type, delay]);
}
return;
}
if (!msg_text) {
var item = SK_drawMessage.queue.shift();
if (!item) {
return;
}
msg_text = item[0];
type = item[1];
delay = item[2];
}
SK_drawMessage.in_process = true;
// getting draw position
var $last = jQuery('.macos_msg_node:last');
var top_pos = (!$last.length) ? 0 : $last.position().top + $last.outerHeight() + 2;
var $msg_block =
// creating message block
jQuery('<div class="macos_msg_node macos_'+type+'" style="display: none"></div>')
.appendTo('body')
.html(msg_text)
.prepend('<a class="close_btn" href="#"></a>')
.css('top', top_pos)
.fadeTo(50, 0.1, function() {
jQuery(this).css('display', '');
SK_drawMessage.in_process = false;
SK_drawMessage();
jQuery(this).fadeTo(300, 1, function() {
if (delay > 0) {
window.setTimeout(function() {
try {
$msg_block.fadeOut(2500, function() {
jQuery(this).remove();
});
} catch (e) {alert(e);}
}, delay);
}
});
});
$msg_block.children('.close_btn')
.click(function() {
jQuery(this).parent().fadeOut(100, function() {
jQuery(this).remove();
});
return false;
}
);
}
SK_drawMessage.in_process = false;
SK_drawMessage.queue = [];
/**
* Float box constructor.
*
* #param string|jQuery $title
* #param string|jQuery $contents
* #param jQuery $controls
* #param object position {top, left} = center
* #param integer width = auto
* #param integer height = auto
*/
function SK_FloatBox(options)
{
var fb_class;
if (typeof document.body.style.maxHeight === 'undefined') { //if IE 6
jQuery('body').css({height: '100%', width: '100%'});
jQuery('html').css('overflow', 'hidden');
if (document.getElementById('floatbox_HideSelect') === null) { //iframe to hide select elements in ie6
jQuery('body').append('<iframe id="floatbox_HideSelect"></iframe><div id="floatbox_overlay"></div>');
fb_class = SK_FloatBox.detectMacXFF() ? 'floatbox_overlayMacFFBGHack' : 'floatbox_overlayBG';
jQuery('#floatbox_overlay').addClass(fb_class);
}
}
else { //all others
if (document.getElementById('floatbox_overlay') === null) {
jQuery('body').append('<div id="floatbox_overlay"></div>');
fb_class = SK_FloatBox.detectMacXFF() ? 'floatbox_overlayMacFFBGHack' : 'floatbox_overlayBG';
jQuery('#floatbox_overlay').addClass(fb_class);
}
}
jQuery('body').css('overflow', 'hidden');
this.$container = jQuery('.floatbox_container', '#sk-floatbox-block-prototype').clone().appendTo('body');
this.$header = this.$container.find('.block_cap_title');
if (typeof options.$title == 'string') {
options.$title = jQuery('<span>'+options.$title+'</span>');
}
else {
this.$title_parent = options.$title.parent();
}
this.$header.append(options.$title);
this.$body = this.$container.find('.block_body_c');
if (typeof options.$contents == 'string') {
options.$contents = jQuery('<span>'+options.$contents+'</span>');
}
else {
this.$contents_parent = options.$contents.parent();
}
this.$body.append(options.$contents);
this.$bottom = this.$container.find('.block_bottom_c');
if (options.$controls) {
if (typeof options.$controls == 'string') {
options.$controls = jQuery('<span>'+options.$controls+'</span>');
}
else {
this.$controls_parent = options.$controls.parent();
}
this.$bottom.append(options.$controls);
}
if (options.width)
this.$container.css("width", options.width);
if (options.height)
this.$container.css("height", options.height);
var fl_box = this;
jQuery('.close_btn', this.$container.find('.floatbox_header'))
.one('click', function() {
fl_box.close();
return false;
});
this.esc_listener =
function(event) {
if (event.keyCode == 27) {
fl_box.close();
return false;
}
return true;
}
jQuery(document).bind('keydown', this.esc_listener);
this.$container
.fadeTo(1, 0.1, function()
{
var $this = jQuery(this);
$this.css('display', 'block');
if (options.position) {
$this.css(options.position);
}
else {
var position = {
top:((jQuery(window).height()/2) - ($this.height()/2))/*.ceil()*/,
left:((jQuery(window).width()/2) - ($this.width()/2))/*.ceil()*/
};
$this.css(position);
}
// trigger on show event
fl_box.trigger('show');
$this.fadeTo(100, 1);
});
this.events = {close: [], show: []};
}
SK_FloatBox.detectMacXFF = function()
{
var userAgent = navigator.userAgent.toLowerCase();
return (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1);
}
SK_FloatBox.prototype = {
close: function()
{
if (this.trigger('close') === false) {
return false;
}
jQuery(document).unbind('keydown', this.esc_listener);
if (this.$title_parent && this.$title_parent.length) {
this.$title_parent.append(
this.$header.children()
);
}
if (this.$contents_parent && this.$contents_parent.length) {
this.$contents_parent.append(this.$body.children());
}
if (this.$controls_parent && this.$controls_parent.length) {
this.$controls_parent.append(this.$bottom.children());
}
this.$container.remove();
if (jQuery('.floatbox_container:not("#sk-floatbox-block-prototype .floatbox_container")').length === 0) {
jQuery('body').css('overflow', '');
jQuery('#floatbox_overlay, #floatbox_HideSelect').remove();
}
return true;
},
bind: function(type, func)
{
if (this.events[type] == undefined) {
throw 'form error: unknown event type "'+type+'"';
}
this.events[type].push(func);
},
trigger: function(type, params)
{
if (this.events[type] == undefined) {
throw 'form error: unknown event type "'+type+'"';
}
params = params || [];
for (var i = 0, func; func = this.events[type][i]; i++) {
if (func.apply(this, params) === false) {
return false;
}
}
return true;
}
}
function SK_alert($title, $contents, callback)
{
if (!callback &&
typeof $contents == 'function' &&
$contents.constructor != Array) {
callback = $contents;
}
if (!$contents || $contents == callback) {
$contents = $title;
$title = SK_Language.text('%interface.alert_title');
}
var $ok_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.ok'));
var fl_box = new SK_FloatBox({
$title: $title,
$contents: $contents,
$controls: $ok_btn
});
$ok_btn.one('click', function() {
fl_box.close();
if (callback) {
callback.apply(fl_box);
}
});
return fl_box;
}
function SK_confirm($title, $contents, callback)
{
if (!callback &&
typeof $contents == 'function' &&
$contents.constructor != Array) {
callback = $contents;
}
if (!$contents || $contents == callback) {
$contents = $title;
$title = SK_Language.text('%interface.confirmation_title');
}
var $ok_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.ok'));
var $cancel_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.cancel'));
var fl_box = new SK_FloatBox({
$title: $title,
$contents: $contents,
$controls: jQuery($ok_btn)
.add('<span> </span>')
.add($cancel_btn)
});
$ok_btn.one('click', function() {
fl_box.close();
if (callback) {
callback.apply(fl_box);
}
});
$cancel_btn.one('click', function() {
fl_box.close();
});
return fl_box;
}
function SK_BlockHandler(block_node)
{
this.$block = jQuery(block_node);
this.$block_cap =
jQuery('.block_cap:eq(0)', this.$block);
this.$title =
jQuery('.block_cap_title:eq(0)', this.$block_cap);
this.$body =
jQuery('.block_body:eq(0)', this.$block);
this.$expand_btn =
jQuery('.block_expand:eq(0), .block_collapse:eq(0)', this.$block_cap);
this.events = {
click: [],
expand: [],
collapse: []
}
var handler = this;
this.$block_cap
.click(function() {
if (handler.$expand_btn.hasClass('block_expand')) {
handler.expand();
}
else if (handler.$expand_btn.hasClass('block_collapse')) {
handler.collapse();
}
return false;
});
}
SK_BlockHandler.prototype = {
expand: function(trigger_events)
{
if (trigger_events === undefined) {
trigger_events = true;
}
if (!trigger_events || (
this.trigger('expand') !== false
&& this.trigger('click') !== false)
) {
this.$expand_btn.attr('class', 'block_collapse');
this.$body.slideDown('fast');
}
return this;
},
collapse: function(trigger_events)
{
if (trigger_events === undefined) {
trigger_events = true;
}
if (!trigger_events || (
this.trigger('collapse') !== false
&& this.trigger('click') !== false)
) {
this.$expand_btn.attr('class', 'block_expand');
this.$body.slideUp('fast');
}
return this;
},
show: function(speed, callback) {
this.$block.show(speed, callback);
},
hide: function(speed, callback) {
this.$block.hide(speed, callback);
},
bind: function(type, arg1, arg2)
{
if (this.events[type] == undefined) {
throw 'block error: unknown event type "'+type+'"';
}
if (!arg2) {
this.events[type].push([arg1]);
}
else {
this.events[type].push([arg1, arg2]);
}
},
trigger: function(type)
{
if (this.events[type] == undefined) {
throw 'block error: unknown event type "'+type+'"';
}
for (var i = 0, item; item = this.events[type][i]; i++)
{
if (item.length == 1) {
if (item[0].apply(this) === false) {
return false;
}
}
else if (item[1].call(this, item[0]) === false) {
return false;
}
}
return true;
},
clone: function(clone_e)
{
var $clone = this.$block.clone();
var node = $clone.get(0);
node.sk_block_handler = new SK_BlockHandler(node);
if (clone_e) {
node.sk_block_handler.events = this.events;
}
return node.sk_block_handler;
},
append: function(content) {
return this.$body.append(content);
return this;
},
appendTo: function(content) {
this.$block.appendTo(content);
return this;
},
empty: function() {
this.$body.empty();
return this;
},
children: function(expr) {
return this.$body.children(expr).not('.block_body_corner');
},
find: function(expr) {
return this.$body.find(expr).not('.block_body_corner');
},
removeAttr: function(name) {
this.$block.removeAttr(name);
return this;
},
addClass: function(cls) {
this.$block.addClass(cls);
return this;
},
removeClass: function(cls) {
this.$block.removeClass(cls);
return this;
}
}
jQuery(function() {
jQuery('.block_expand, .block_collapse')
.each(function() {
var block_node = this.parentNode.parentNode.parentNode.parentNode;
if (jQuery(block_node).hasClass('block')) {
block_node.sk_block_handler = new SK_BlockHandler(block_node);
}
});
});
SK_Language = {
data: {},
text: function(lang_addr, var_list)
{
if ( SK_Language.data[lang_addr] === undefined ) {
throw new SK_Exception('language section ['+lang_addr+'] not found');
}
var text = SK_Language.data[lang_addr];
if (var_list) {
for ( key in var_list ) {
text = text.replace('{$'+key+'}', var_list[key]);
}
}
return text;
}
}
function nl2br(str) {
return (str + '').replace(/([^>]?)\n/g, '$1<br />\n');
}
function SK_SignIn() {
return window.sk_component_sign_in.showBox();
}
function SK_openIM(opponent_id, is_esd)
{
if (is_esd)
is_esd_session = '&is_esd_session='+is_esd;
else
is_esd_session = '';
return window.open(
URL_MEMBER+'im.php?opponent_id='+opponent_id+is_esd_session,
'im_with_'+opponent_id,
'width='+SK_openIM.width+','+
'height='+SK_openIM.height+','+
'resizable=yes, location=no, scrollbars=no, status=no'
);
}
SK_openIM.width = 445;
SK_openIM.height = 460;
function SK_profileNote( event_id, opponent_id)
{
return window.open(
URL_MEMBER+'profile_note.php?event_id='+event_id+'&opponent_id='+opponent_id,
'note_'+opponent_id,
'width='+SK_profileNote.width+','+
'height='+SK_profileNote.height+','+
'resizable=yes, location=no, scrollbars=no, status=no'
);
}
SK_profileNote.width = 325;
SK_profileNote.height = 425;
SK_EventManager = {
events: {},
bind: function(event, callback)
{
if ( typeof this.events[event] == 'undefined' || this.events[event] === null)
{
this.events[event] = [];
}
this.events[event].push(callback);
},
trigger: function(event, eventObject)
{
if (typeof this.events[event] != 'undefined' && this.events[event] !== null)
{
for (var i = 0; i < this.events[event].length; i++)
{
if (typeof this.events[event][i] == 'function')
{
if (this.events[event][i](eventObject) === false)
{
return;
}
}
}
}
}
};
SK_SetFieldInvitation = function(id, label)
{
var $node = $('#' + id);
$node.addClass('input_invitation').val(label);
$node.focus(function() {
var v = $node.val();
$node.removeClass('input_invitation');
if ( v == label )
{
$node.val('');
}
}).blur(function() {
var v = $node.val();
if ( !v )
{
$node.addClass('input_invitation').val(label);
}
});
$($node.get(0).form).submit(function(){
if ( $node.val() != label )
{
$node.removeClass('input_invitation');
}
});
}
<div class="floatbox_container" style="overflow: visible; width: 320px; opacity: 0.1; display: block; top: 274px; left: 736px;">
<div class="block_cap floatbox_header"><div class="block_cap_r"><div class="block_cap_c clearfix"><h3 class="block_cap_title"><b>Şifremi unuttum!</b></h3><a class="close_btn" href="#"></a></div></div></div> <div class="floatbox_body">
<div class="fblock_body block_body">
<div class="fblock_body_r block_body_r">
<div class="fblock_body_c block_body_c">
<div class="block_info">Şifremi yenile</div><form id="form_3" method="post" onsubmit="return false;">
<label>E-posta</label>: <input id="form_3-email" name="email" type="text" maxlength="255">
<div id="form_3-email-container"></div>
<div class="controls center float_left">
<input id="form_3-send-button" type="submit" value="Gönder"> </div>
<div class="clr"></div>
</form></div>
</div>
</div>
</div>
<div class="floatbox_bottom">
<div class="block_bottom">
<div class="block_bottom_r">
<div class="block_bottom_c">
</div>
</div>
</div>
</div>
<div class="fblock_bottom">
<div class="fblock_bottom_r">
<div class="fblock_bottom_c"></div>
</div>
</div>
</div>

Delete specific item from local storage

I have a note taking application that im working on . Its made to look like Google Keep
It saves each note in local storage .
I would like to add a delete option to each of the notes (similar to Keep) , but don't know know to do it.
The full code is on my Github page https://github.com/oxhey/keep
HTML :
<!doctype html>
<html>
<head>
<title>Notes</title>
<link href="styles/normalize.css" rel="stylesheet" />
<link href="styles/main.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="window.css">
</head>
<script>
var nw = require('nw.gui');
var win = nw.Window.get();
win.isMaximized = false;
</script>
<body id="gui">
<header class="app-header">
<ul style="margin-top:0.3px">
<li><a href='#' title='Close' id='windowControlClose'></a></li>
<li><a href='#' title='Maximize' id='windowControlMaximize'></a></li>
<li><a href='#' title='Minimize' id='windowControlMinimize'></a></li>
</ul>
<h2 style="margin-top: 10px;margin-left: 20px;color: #fff;">Notes</h2>
</header>
<section class="main-section">
<article class="note add-note">
<h1 class="note-title"></h1>
<p class="note-content">Add a note</p>
</article>
</section>
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
<script>
// Min
document.getElementById('windowControlMinimize').onclick = function()
{
win.minimize();
};
// Close
document.getElementById('windowControlClose').onclick = function()
{
win.close();
gui.App.closeAllWindows();
};
// Max
document.getElementById('windowControlMaximize').onclick = function()
{
if (win.isMaximized)
win.unmaximize();
else
win.maximize();
};
win.on('maximize', function(){
win.isMaximized = true;
});
win.on('unmaximize', function(){
win.isMaximized = false;
});
</script>
</body>
</html>
Javascript : Main.js
var Strings = {
'en-us': {
DEFAULT_TITLE: "Title",
ADD_NOTE: "Add a note",
SEARCH_PLACEHOLDER: "Search Jin's Keep"
}
};
var Lang = Strings['en-us'];
var Keys = {
ENTER: 10
}
var notes;
function Note(title, content, id) {
Note.numInstances = (Note.numInstances || 0) + 1;
this.id = id ? id : Note.numInstances
this.title = title;
this.content = content;
}
Note.prototype.render = function(index) {
var elem = $('<article class="note" data-index="' + index + '"><h1 class="note-title">' + this.title + '</h1><p class="note-content">' + this.content + '</p></article>');
$(".add-note").after(elem);
}
Note.prototype.toJSON = function() {
return {
id: this.id,
title: this.title,
content: this.content
};
}
function createNote() {
var elem = $(".add-note");
var title = elem.find(".note-title");
var content = elem.find(".note-content");
elem.removeClass("active");
title.hide();
if(title.text() != Lang.DEFAULT_TITLE || content.text() != Lang.ADD_NOTE) {
var id = notes ? notes.length+1 : 1;
var note = new Note(title.text(), content.text(), id);
notes.push(note);
note.render(notes.length-1);
title.text(Lang.DEFAULT_TITLE);
content.text(Lang.ADD_NOTE);
saveNotes();
}
}
function activateNote(note) {
var title = note.find(".note-title");
note.addClass("active");
title.show();
if(isEmpty(title.text())) {
title.text(Lang.DEFAULT_TITLE);
}
}
function saveCurrentNote() {
var noteElement = $(".note.active");
if(noteElement) {
console.log("will save this element: ", noteElement[0]);
var noteIndex = noteElement.attr("data-index");
var note = notes[noteIndex];
note.title = noteElement.find(".note-title").text();
note.content = noteElement.find(".note-content").text();
saveNotes();
deactivateCurrentNote(noteElement);
}
}
function deactivateCurrentNote(note) {
note.removeClass("active");
var title = note.find(".note-title");
if(isEmpty(title.text()) || title.text() == Lang.DEFAULT_TITLE) {
title.hide();
}
$(":focus").blur();
}
function isEmpty(string) {
return string.replace(/\s| /g, '').length == 0;
}
function addTabIndex() {
tabIndex = 3;
$(".note .note-content, .note .note-title").each(function() {
var el = $(this);
el.attr("tabindex", tabIndex++);
});
}
function loadNotes() {
var rawObjects = JSON.parse(localStorage.getItem("notes"));
if(rawObjects && rawObjects.length) {
rawObjects.forEach(function(obj, index) {
obj.__proto__ = Note.prototype;
obj.render(index);
});
return rawObjects;
} else {
console.warn("Couldn't load any note because local storage is empty.");
return [];
}
}
function saveNotes() {
localStorage.setItem("notes", JSON.stringify(notes))
}
$(document).ready(function() {
notes = loadNotes();
addTabIndex();
$(".note").each(function() {
var note = $(this);
var title = note.find(".note-title");
if(isEmpty(title.text()) || title.text() == Lang.DEFAULT_TITLE ) {
title.hide();
}
});
$(".main-section").on("click", ".note .note-content, .note .note-title", function(evt) {
var note = $(this).parent();
activateNote(note);
//console.log('2 - Setting content editable to true', evt);
var noteSection = $(this);
noteSection.prop("contentEditable", true);
});
$(".main-section").on("click", ".note .note-title", function(evt) {
//console.log("3 - Clearing TITLE's text");
var title = $(this);
if(title.text() == Lang.DEFAULT_TITLE) {
title.text("");
}
});
$(".main-section").on("click", ".note .note-content", function(evt) {
//console.log('4 - Clearing CONTENT text', evt);
var content = $(this);
if(content.text() == Lang.ADD_NOTE) {
content.text("");
content.focus();
}
});
$(".main-section").on("click", function(evt) {
if(evt.target == this) {
//console.log('5', evt);
var currentNote = $(".note.active");
if(currentNote.length) {
//console.log('5.a');
if(currentNote.hasClass("add-note")) {
console.log('5 - Creating a new note');
createNote();
} else {
console.log('5 - Saving current note');
saveCurrentNote();
}
if(currentNote.find(".note-title").text() == Lang.DEFAULT_TITLE) {
currentNote.find(".note-title").hide();
}
}
}
});
$(".main-section").on("keypress", ".note .note-content, .note .note-title", function(evt) {
var currentNote = $(".note.active");
console.log('6');
if(evt.which == Keys.ENTER && evt.ctrlKey) {
console.log('2');
if(currentNote.hasClass("add-note")) {
createNote();
} else {
saveCurrentNote();
}
}
});
});
Thanks
Something like this? Use a data attribute on a delete button and pass that as a parameter to a removeNote function.
HTML
<button class="delete" data-id="1">Delete note</button>
JS
$(document).on('click', '.delete', function () {
var id = $(this).data('id');
removeNote(id);
});
function removeNote(id) {
localStorage.removeItem(id);
}

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

jQuery error with Quick Search Results box

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

Preloading images in a slider

This slider works but I just need to preload images:
document.observe("dom:loaded", function(event) {
initSlider()
});
var slider_index = 0;
var auto_scroll = true;
var ctime = false;
function initSlider() {
$('slider-img').src = slider_images[0];
$('slider-text').innerHTML = slider_text[0];
$('slider-link').setAttribute('href',slider_links[0]);
ctime = window.setTimeout(function() {
sliderNext(true);
},7000);
}
function sliderPrev() {
changeSlide(slider_index-1);
clearTimeout(ctime);
}
function sliderNext(scroll) {
if (scroll == true) {
ctime = window.setTimeout(function() {
sliderNext(true);
},21000);
} else {
clearTimeout(ctime);
}
changeSlide(slider_index+1, scroll);
}
function changeSlide(target, auto) {
if (auto) auto_scroll = true; else auto_scroll = false;
if (!auto_scroll) clearTimeout(ctime);
var name = "slider_thumb" + slider_index;
$(name).removeClassName("active");
slider_index = target;
if ( slider_index >= slider_count ) {
slider_index = 0;
} else if ( slider_index < 0 ) {
slider_index = slider_count - 1;
}
$('slider-img').src = slider_images[slider_index];
$('slider-text').innerHTML = slider_text[slider_index];
$('slider-link').setAttribute('href',slider_links[slider_index]);
var name = "slider_thumb" + slider_index;
$(name).addClassName("active");
}
// Preload Image
$('<img />')
.attr('src', 'picture.jpg')
.load(function(){
$('.slider').append( $(this) );
// some other Code
});

Categories