condense multiple instances into one - javascript

i've got a little code in in my main.js file that i've been using for activating various popover [bootstrap] buttons throughout the page.
// popover 1
var $btn1 = $('#btn1');
$btn1.data('state', 'hover');
var enterShow = function () {
if ($btn1.data('state') === 'hover') {
$btn1.popover('show');
}
};
var exitHide = function () {
if ($btn1.data('state') === 'hover') {
$btn1.popover('hide');
}
};
var clickToggle = function () {
if ($btn1.data('state') === 'hover') {
$btn1.data('state', 'pinned');
} else {
$btn1.data('state', 'hover')
$btn.popover('hover');
}
};
$btn1.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.on('click', clickToggle);
// popover 2
var $btn2 = $('#btn2');
$btn2.data('state', 'hover');
var enterShow = function () {
if ($btn2.data('state') === 'hover') {
$btn2.popover('show');
}
};
var exitHide = function () {
if ($btn2.data('state') === 'hover') {
$btn2.popover('hide');
}
};
var clickToggle = function () {
if ($btn2.data('state') === 'hover') {
$btn2.data('state', 'pinned');
} else {
$btn2.data('state', 'hover')
$btn.popover('hover');
}
};
$btn2.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.on('click', clickToggle);
but the more buttons (popovers) i add, the more instances of this i have to keep putting in the main.js.
QUESTION:
is there a multiplier i can use to achieve this result with just one instance of the code instead of an instance for each popover.

Question is not very clear to me but if you just want to make the same initialisation on differents buttons, then just create a function for it.
function initPopover(selector){
var $btn1 = $(selector);
$btn1.data('state', 'hover');
var enterShow = function () {
if ($btn1.data('state') === 'hover') {
$btn1.popover('show');
}
};
var exitHide = function () {
if ($btn1.data('state') === 'hover') {
$btn1.popover('hide');
}
};
var clickToggle = function () {
if ($btn1.data('state') === 'hover') {
$btn1.data('state', 'pinned');
} else {
$btn1.data('state', 'hover')
$btn.popover('hover');
}
};
$btn1.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.on('click', clickToggle);
}

Instead of using a fixed variable name inside the event handler, use $(this), which references the element the handler is bound to:
$('#btn1 #btn2') // <- note that I'm selecting both buttons
.data('state', 'hover')
.popover({trigger: 'manual'})
.on({
mouseenter: function() {
if ($(this).data('state') === 'hover') {
$(this).popover('show');
}
},
mouseleave: function() {
if ($(this).data('state') === 'hover') {
$(this).popover('hide');
}
},
click: function () {
if ($(this).data('state') === 'hover') {
$(this).data('state', 'pinned');
} else {
$(this).data('state', 'hover')
$(this).popover('hover');
}
}
});
I recommend to read the jQuery tutorial to learn more about event handlers, where it says:
In addition to the event object, the event handling function also has access to the DOM element that the handler was bound to via the keyword this. To turn the DOM element into a jQuery object that we can use jQuery methods on, we simply do $( this ) [...]

Related

Combining click and dbclick

How I am supposed to combine the below ones into one single working script?
When is clicked once a color picked-up by user appears,click again the color turns in white and when double-clicked appears aqua. It is too long code, I tried to combine them, but I made mistake.
//single click
$('#pixel_canvas').on('click', 'td', function () {
var color = $('#colorPicker').val();
if ($(this).hasClass("blank") == true) {
$(this).css('background-color', color);
$(this).removeClass('blank');
}
else {
$(this).addClass('blank');
$(this).css('background-color', 'white');
}
});
//double click
$('#pixel_canvas').on('dblclick', 'td', function () {
var color = $('#colorPicker').val();
if ($(this).hasClass("blank") == true) {
$(this).css('background-color', color);
$(this).removeClass('blank');
}
else {
$(this).addClass('blank');
$(this).css('background-color', 'aqua');
}
});
I'd go something like this:
// Take your actual 'core' code and turn it into a jQuery function:
$.fn.setColor(colorOff){
if( $(this).hasClass("blank") ){
$(this)
.css('background-color', $('#colorPicker').val())
.removeClass('blank');
} else{
$(this)
.addClass('blank')
.css('background-color',colorOff);
}
}
// Now bind the events to the element and pass the color needed for the events:
$('#pixel_canvas')
.on('click','td',function(){
$(this).setColor('white')
})
.on('dblclick','td',function(){
$(this).setColor('aqua')
});
This may help.
function doClickAction() {
var color=$('#colorPicker').val();
if($(this).hasClass("blank")==true){
$(this).css('background-color',color);
$(this).removeClass('blank');
}
else{
$(this).addClass('blank');
$(this).css('background-color','white');
}
}
function doDoubleClickAction() {
var color=$('#colorPicker').val();
if($(this).hasClass("blank")==true){
$(this).css('background-color',color);
$(this).removeClass('blank');
}
else{
$(this).addClass('blank');
$(this).css('background-color','aqua');
}
}
var timer = 0;
var delay = 200;
var prevent = false;
$("#pixel_canvas")
.on("click", function() {
timer = setTimeout(function() {
if (!prevent) {
doClickAction();
}
prevent = false;
}, delay);
})
.on("dblclick", function() {
clearTimeout(timer);
prevent = true;
doDoubleClickAction();
});

Cursor pointer moves to first position onclick textarea using CK-Editor

I am using CK-Editor 4. In which I have created Directive. When I click on Textarea my cursor pointer is Move to First position. I want my cursor position should be available when I click in any of the Place inside Textarea. It should not be able to move first or last position until I click on last position.
vpb.directive('ckeInline', function ($timeout, $parse, $rootScope,$) {
return {
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
if (attrs.ckeInlineShowtitle) ngModel = "";
isMobile = $(".ipad, .ipod, .android").length > 0;
var destroy_this_editor = function(id)
{
setTimeout(function () {
try{
CKEDITOR.instances[id].destroy(true);
} catch (ex) {
}
},500)
}
if (!isMobile) {
var create_and_focus = function () {
if (scope.setup.edit_mode || attrs.ckeNonEditMode) {
attrs.$set('contenteditable', true);
var a_id = attrs.ckeInlineId;
var menu_selector = attrs.ckeInlineMenu;
//get editor
//create editor if doesn't exist
var e = CKEDITOR.instances[a_id];
if (!e) {
element.menu = $(menu_selector);
//set up behavior for menu
uif.wire_up_menu(element, scope);
//hide all menu bars
$("nav.text-editor-menu-bar").hide();
//create editor
var config = {
toolbar: "More",
on: {
'blur': function () {
save_editor_content(function () {
destroy_this_editor(a_id);
});
},
'focusout': function () {
save_editor_content(function () {
destroy_this_editor(a_id);
});
},
'focus': function () {
//show the current menu
element.menu.show();
//fix menu width
uif.stretch_menu(element);
},
'instanceReady': function (event,element) {
//----------------I think,Here i want logic to set caret sign or set mouse
//pointer to appropriate place
// event.editor.focus();
// element.focus();
}
}
};
if (attrs.ckeInlineToolbar) {
config.toolbar = attrs.ckeInlineToolbar;
}
var editor = CKEDITOR.inline(a_id, config);
if (attrs.ckeInlineOnInit) {
uif.apply_scope($rootScope, $parse(attrs.ckeInlineOnInit));
}
}
else
{
e.focus();
element.focus();
}
} else
{
attrs.$set('contenteditable', false);
}
}
element.click(function () {
create_and_focus();
});
if (attrs.ckeInlineFocusWatch) {
scope.$watch(function () {
return $parse(attrs.ckeInlineFocusWatch);
}, function () {
if (attrs.ckeInlineFocusCondition == undefined || $parse(attrs.ckeInlineFocusCondition)() == true) {
create_and_focus();
}
})
}
var saving = false;
var save_editor_content = function (cb) {
if (!saving)
{
saving = true;
var a_id = attrs.ckeInlineId;
if (a_id) {
var editor = CKEDITOR.instances[a_id];
if (editor) {
var menu_selector = attrs.ckeInlineMenu;
element.menu.hide();
//attrs.$set('contenteditable', false);
var newValue = editor.getData().replace(/ /, ' ');
if (ngModel.$modelValue != newValue) {
if (attrs.ckeInlineBlurBool) {
$parse(attrs.ckeInlineBlurBool).assign($rootScope, false);
}
ngModel.$setViewValue(newValue);
if (attrs.ckeInlineSave) {
uif.apply_scope(scope, $parse(attrs.ckeInlineSave));
}
$timeout(function () {
saving = false;
if (cb) cb();
}, 1100)
} else
{
saving = false;
$rootScope.setup.blcok_edits = false;
$rootScope.setup.block_all_editors = false;
if (cb) cb();
}
}
}
else
{
saving = false;
}
}
};
} else if (attrs.ckeNonEditMode) {
attrs.$set('contenteditable', true);
element.blur(function () {
ngModel.$setViewValue(element.html().replace(/ /, ' '));
if (attrs.ckeInlineSave) {
uif.apply_scope(scope, $parse(attrs.ckeInlineSave));
}
})
}
}
}
});

Closing a menu on anywhere click

I am working on a website and here is the link file:///D:/fahim/HTML/menu/index.html. If you click the menu its closing on its own "X" button, but i want it to close by clicking outside the menu. This is the javascript used on the home page.
<script>
var popupView = new popup();
document.querySelector('#btn_1').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_1'));
});
document.querySelector('#btn_2').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_2'), function () {
console.log('show do something');
});
});
document.querySelector('#btn_3').addEventListener('click', function () {
popupView.show(document.querySelector('#popup_3'), '', function () {
console.log('CLOSE');
});
});
</script>
And this is the code which is attached as popup_view.js file on server
(function () {
var popup = function() {
function hide(dom, dosomething) {
if (!dom) {
console.error('hide function not set dom object');
return;
}
if (dosomething) {
dosomething();
}
dom.className += ' ' + 'popup_hide';
}
function show(dom, dosomethingShow, dosomethingClose) {
if (!dom) {
console.error('show function not set dom object');
return;
}
if (dosomethingShow) {
dosomethingShow();
}
var className = 'popup_hide',
reg = new RegExp('(^|\\b)' +
className.split(' ').join('|') +
'(\\b|$)', 'gi');
dom.className = dom.className.replace(reg, '').trim();
var nodes = dom.childNodes;
for (var i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].className === 'pop_up_close') {
var close = function (e) {
if (dosomethingClose) {
dosomethingClose();
}
dom.className += ' ' + 'popup_hide';
nodes[i].removeEventListener('click', close);
};
nodes[i].addEventListener('click', close);
break;
}
}
}
this.show = show;
this.hide = hide;
};
window.popup = popup;
})();
Please help as i have tried lot of codes except these but non of them works
$(document).on('click', function(e){
//your close function
e.stopPropagation();
}
Put that code anywhere in your $(document).ready(... block

Close dropdown with animation

I would like to add a listener that listens for a click on 'html' and then closes the dropdown. It only ever works without the hide function by puttind css display to none. Nothing seems to work!!
Any ideas?
// Drop Down Menu
EZEMAIN.dropDown = {
slideTime: 200,
dropDown: '.dn-drop-down',
arrow: '.dn-menu-arrow',
arrowUp: 'dn-arrow-up',
bindElms: function () {
this.btn = $('.dn-dropdown-btn');
},
html: function(e) {
},
showHide: function (e) {
var self = EZEMAIN.dropDown,
dropDown = $(this).find(self.dropDown),
arrow = $(this).find(self.arrow),
openedDropDowns = $(self.dropDown).is(':visible');
if ($(e.target).parents(self.dropDown).length == 0)
e.preventDefault();
if (dropDown.is(':hidden')) {
if (openedDropDowns) self.hide();
dropDown.slideDown(self.slideTime, function () {
arrow.addClass(self.arrowUp);
});
setTimeout(function () {
$('body').on('click', self.hide);
}, 100);
}
else
self.hide();
},
hide: function () {
var self = EZEMAIN.dropDown;
$(self.dropDown).slideUp(self.slideTime, function () {
$(self.arrow).filter(function () { return $(this).siblings('.dn-basket-btn').length == 0; }).removeClass(self.arrowUp);
});
$("html").click(function () {
//$("#dn-header-basket").css("display", "none");
$(EZEMAIN.arrow).filter(function () { return $(this).siblings('.dn-menu-arrow').length == 0; }).removeClass(self.arrowUp);
});
$('body').off('click', self.hide);
},
init: function () {
this.bindElms();
this.btn.click(this.showHide);
}
};

Manually calling PDFJS functions. What func to call after PDFView.open to render

CanĀ“t find in the documentation what to do next.
Calling:
PDFView.open('/MyPDFs/Pdf1.pdf', 'auto', null)
I am able to see the blank pages, the loader and also the document gets the number of pages of my PDF.
The only thing is missing is the rendering.
Does anyone knows what I should call next?
Thanks
$(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
In viewer.js I added call to updateViewarea() after the document was downloaded.
... PDFJS.getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
updateViewarea();
}, ...

Categories

Resources