fullscreen api not working for IE - javascript

I am trying to display content in full screen in IE using Full Screen API everything works fine except IE below is code, any help would be great.thank you in advance.
JAVASCRIPT CODE:
(function() {
var
fullScreenApi = {
supportsFullScreen: false,
isFullScreen: function() { return false; },
requestFullScreen: function() {},
cancelFullScreen: function() {},
fullScreenEventName: '',
prefix: ''
},
browserPrefixes = 'webkit moz o ms khtml'.split(' ');
// check for native support
if (typeof document.cancelFullScreen != 'undefined') {
fullScreenApi.supportsFullScreen = true;
} else {
// check for fullscreen support by vendor prefix
for (var i = 0, il = browserPrefixes.length; i < il; i++ ) {
fullScreenApi.prefix = browserPrefixes[i];
if (typeof document[fullScreenApi.prefix + 'CancelFullScreen' ] != 'undefined' ) {
fullScreenApi.supportsFullScreen = true;
break;
}
}
}
// update methods to do something useful
if (fullScreenApi.supportsFullScreen) {
fullScreenApi.fullScreenEventName = fullScreenApi.prefix + 'fullscreenchange';
fullScreenApi.isFullScreen = function() {
switch (this.prefix) {
case '':
return document.fullScreen;
case 'webkit':
return document.webkitIsFullScreen;
default:
return document[this.prefix + 'FullScreen'];
}
}
fullScreenApi.requestFullScreen = function(el) {
return (this.prefix === '') ? el.requestFullScreen() : el[this.prefix + 'RequestFullScreen']();
}
fullScreenApi.cancelFullScreen = function(el) {
return (this.prefix === '') ? document.cancelFullScreen() : document[this.prefix + 'CancelFullScreen']();
}
}
// jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.requestFullScreen = function() {
return this.each(function() {
var el = jQuery(this);
if (fullScreenApi.supportsFullScreen) {
fullScreenApi.requestFullScreen(el);
}
});
};
}
// export api
window.fullScreenApi = fullScreenApi;
})();
</script>
<script>
var fsButton = document.getElementById('fsbutton');
var fsElement = document.getElementById('container');
if (window.fullScreenApi.supportsFullScreen) {
// handle button click
fsButton.addEventListener('click', function() {
//alert(fsElement);
window.fullScreenApi.requestFullScreen(fsElement);
//alert("hi");
}, true);
fsElement.addEventListener(fullScreenApi.fullScreenEventName, function() {
if (fullScreenApi.isFullScreen()) {
alert("yes");
//fsStatus.innerHTML = 'Whoa, you went fullscreen';
} else {
alert("no");
// fsStatus.innerHTML = 'Back to normal';
}
}, true);
} else {
alert("no");
// fsStatus.innerHTML = 'SORRY: Your browser does not support FullScreen';
}
</script>
HTML CODE:
<div>
<div id="container" >
..... content goes here
</div>
<input type="button" id="fsbutton" title="View Full Screen">
</div>

I didn't try it but I think that it's because IE doesn't use the camelCase for "Fullscreen" in "cancelFullscreen" and "requestFullscreen", which is the actual live standard recommandation btw.
Other browsers are wrong this time.

Related

I want to add a loading png in LiveSearch

I am using a plugin for live search .. everything is working fine .. i just want to add a loading png that appear on start of ajax request and disappear on results ..
please help me to customize the code just to add class where form id="search-kb-form" .. and remove the class when results are completed.
<form id="search-kb-form" class="search-kb-form" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="wrapper-kb-fields">
<input type="text" id="s" name="s" placeholder="Search what you’re looking for" title="* Please enter a search term!">
<input type="submit" class="submit-button-kb" value="">
</div>
<div id="search-error-container"></div>
</form>
This is the plugin code
jQuery.fn.liveSearch = function (conf) {
var config = jQuery.extend({
url: {'jquery-live-search-result': 'search-results.php?q='},
id: 'jquery-live-search',
duration: 400,
typeDelay: 200,
loadingClass: 'loading',
onSlideUp: function () {},
uptadePosition: false,
minLength: 0,
width: null
}, conf);
if (typeof(config.url) == "string") {
config.url = { 'jquery-live-search-result': config.url }
} else if (typeof(config.url) == "object") {
if (typeof(config.url.length) == "number") {
var urls = {}
for (var i = 0; i < config.url.length; i++) {
urls['jquery-live-search-result-' + i] = config.url[i];
}
config.url = urls;
}
}
var searchStatus = {};
var liveSearch = jQuery('#' + config.id);
var loadingRequestCounter = 0;
// Create live-search if it doesn't exist
if (!liveSearch.length) {
liveSearch = jQuery('<div id="' + config.id + '"></div>')
.appendTo(document.body)
.hide()
.slideUp(0);
for (key in config.url) {
liveSearch.append('<div id="' + key + '"></div>');
searchStatus[key] = false;
}
// Close live-search when clicking outside it
jQuery(document.body).click(function(event) {
var clicked = jQuery(event.target);
if (!(clicked.is('#' + config.id) || clicked.parents('#' + config.id).length || clicked.is('input'))) {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
});
}
});
}
return this.each(function () {
var input = jQuery(this).attr('autocomplete', 'off');
var liveSearchPaddingBorderHoriz = parseInt(liveSearch.css('paddingLeft'), 10) + parseInt(liveSearch.css('paddingRight'), 10) + parseInt(liveSearch.css('borderLeftWidth'), 10) + parseInt(liveSearch.css('borderRightWidth'), 10);
// Re calculates live search's position
var repositionLiveSearch = function () {
var tmpOffset = input.offset();
var tmpWidth = input.outerWidth();
if (config.width != null) {
tmpWidth = config.width;
}
var inputDim = {
left: tmpOffset.left,
top: tmpOffset.top,
width: tmpWidth,
height: input.outerHeight()
};
inputDim.topPos = inputDim.top + inputDim.height;
inputDim.totalWidth = inputDim.width - liveSearchPaddingBorderHoriz;
liveSearch.css({
position: 'absolute',
left: inputDim.left + 'px',
top: inputDim.topPos + 'px',
width: inputDim.totalWidth + 'px'
});
};
var showOrHideLiveSearch = function () {
if (loadingRequestCounter == 0) {
showStatus = false;
for (key in config.url) {
if( searchStatus[key] == true ) {
showStatus = true;
break;
}
}
if (showStatus == true) {
for (key in config.url) {
if( searchStatus[key] == false ) {
liveSearch.find('#' + key).html('');
}
}
showLiveSearch();
} else {
hideLiveSearch();
}
}
};
// Shows live-search for this input
var showLiveSearch = function () {
// Always reposition the live-search every time it is shown
// in case user has resized browser-window or zoomed in or whatever
repositionLiveSearch();
// We need to bind a resize-event every time live search is shown
// so it resizes based on the correct input element
jQuery(window).unbind('resize', repositionLiveSearch);
jQuery(window).bind('resize', repositionLiveSearch);
liveSearch.slideDown(config.duration)
};
// Hides live-search for this input
var hideLiveSearch = function () {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
for (key in config.url) {
liveSearch.find('#' + key).html('');
}
});
};
input
// On focus, if the live-search is empty, perform an new search
// If not, just slide it down. Only do this if there's something in the input
.focus(function () {
if (this.value.length > config.minLength ) {
showOrHideLiveSearch();
}
})
// Auto update live-search onkeyup
.keyup(function () {
// Don't update live-search if it's got the same value as last time
if (this.value != this.lastValue) {
input.addClass(config.loadingClass);
var q = this.value;
// Stop previous ajax-request
if (this.timer) {
clearTimeout(this.timer);
}
if( q.length > config.minLength ) {
// Start a new ajax-request in X ms
this.timer = setTimeout(function () {
for (url_key in config.url) {
loadingRequestCounter += 1;
jQuery.ajax({
key: url_key,
url: config.url[url_key] + q,
success: function(data){
if (data.length) {
searchStatus[this.key] = true;
liveSearch.find("#" + this.key).html(data);
} else {
searchStatus[this.key] = false;
}
loadingRequestCounter -= 1;
showOrHideLiveSearch();
}
});
}
}, config.typeDelay);
}
else {
for (url_key in config.url) {
searchStatus[url_key] = false;
}
hideLiveSearch();
}
this.lastValue = this.value;
}
});
});
};
add a background to the loading class
.loading {
background:url('http://path_to_your_picture');
}

Unobtrusive date compare validator

So I've been following this tutorial here and it shows you how to validate dates compared with each other. I'm getting an error in the first block of code which I've commented and it says "Unable to get property 'element' of undefined or null reference" which originates from this line of code customValidation.formValidator = $(event.data.source).closest('form').data('validator') does anyone know of a work around for this so I don't get an error. I'm using the latest unobtrusive validation
window.customValidation = window.customValidation ||
{
relatedControlValidationCalled: function (event) {
if (!customValidation.activeValidator) {
customValidation.formValidator = $(event.data.source).closest('form').data('validator');
}
// code error below
customValidation.formValidator.element($(event.data.target));
},
relatedControlCollection: [],
formValidator: undefined,
addDependatControlValidaitonHandler: function (element, dependentPropertyName) {
var id = $(element).attr('id');
if ($.inArray(id, customValidation.relatedControlCollection) < 0) {
customValidation.relatedControlCollection.push(id);
$(element).on(
'blur',
{ source: $(element), target: $('#' + dependentPropertyName) },
customValidation.relatedControlValidationCalled);
}
}
};
adapter:
$.validator.unobtrusive.adapters.add('comparedates', ['otherpropertyname', 'allowequality'],
function (options) {
options.rules['comparedates'] = options.params;
if (options.message) {
options.messages['comparedates'] = options.message;
}
}
);
validator method:
$.validator.addMethod('comparedates', function (value, element, params) {
var otherFieldValue = $('input[name="' + params.otherpropertyname + '"]').val();
if (otherFieldValue && value) {
var currentValue = Date.parse(value);
var otherValue = Date.parse(otherFieldValue);
if ($(element).attr('name').toLowerCase().indexOf('begin') >= 0) {
if (params.allowequality) {
if (currentValue > otherValue) {
return false;
}
} else {
if (currentValue >= otherValue) {
return false;
}
}
} else {
if (params.allowequality) {
if (currentValue < otherValue) {
return false;
}
} else {
if (currentValue <= otherValue) {
return false;
}
}
}
}
customValidation.addDependatControlValidaitonHandler(element, params.otherpropertyname);
return true;
}, '');
Maybe you are loading this code too early, before the form is in the DOM. Make sure your code is protected by $(document).ready(your code here);

JavaScript Preventing User Text Selection

Something in this Curtains.js plug-in is preventing user text selection on my page. When I comment it out, I'm able to select text, when I put it back in, I'm not. Can someone identify it and tell me how to fix it? I'm at my wit's end.
<script>
/*
* Curtain.js - Create an unique page transitioning system
* ---
* Version: 2
* Copyright 2011, Victor Coulon (http://victorcoulon.fr)
* Released under the MIT Licence
*/
(function ( $, window, document, undefined ) {
var pluginName = 'curtain',
defaults = {
scrollSpeed: 400,
bodyHeight: 0,
linksArray: [],
mobile: false,
scrollButtons: {},
controls: null,
curtainLinks: '.curtain-links',
enableKeys: true,
easing: 'swing',
disabled: false,
nextSlide: function() {},
prevSlide: function() {}
};
// The actual plugin constructor
function Plugin( element, options ) {
var self = this;
// Public attributes
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this._ignoreHashChange = false;
this.init();
}
Plugin.prototype = {
init: function () {
var self = this;
// Cache element
this.$element = $(this.element);
this.$li = $(this.element).find('>li');
this.$liLength = this.$li.length;
self.$windowHeight = $(window).height();
self.$elDatas = {};
self.$document = $(document);
self.$window = $(window);
self.webkit = (navigator.userAgent.indexOf('Chrome') > -1 || navigator.userAgent.indexOf("Safari") > -1);
$.Android = (navigator.userAgent.match(/Android/i));
$.iPhone = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
$.iPad = ((navigator.userAgent.match(/iPad/i)));
$.iOs4 = (/OS [1-4]_[0-9_]+ like Mac OS X/i.test(navigator.userAgent));
if($.iPhone || $.iPad || $.Android || self.options.disabled){
this.options.mobile = true;
this.$li.css({position:'relative'});
this.$element.find('.fixed').css({position:'absolute'});
}
if(this.options.mobile){
this.scrollEl = this.$element;
} else if($.browser.mozilla || $.browser.msie) {
this.scrollEl = $('html');
} else {
this.scrollEl = $('body');
}
if(self.options.controls){
self.options.scrollButtons['up'] = $(self.options.controls).find('[href="#up"]');
self.options.scrollButtons['down'] = $(self.options.controls).find('[href="#down"]');
if(!$.iOs4 && ($.iPhone || $.iPad)){
self.$element.css({
position:'fixed',
top:0,
left:0,
right:0,
bottom:0,
'-webkit-overflow-scrolling':'touch',
overflow:'auto'
});
$(self.options.controls).css({position:'absolute'});
}
}
// When all image is loaded
var callbackImageLoaded = function(){
self.setDimensions();
self.$li.eq(0).addClass('current');
self.setCache();
if(!self.options.mobile){
if(self.$li.eq(1).length)
self.$li.eq(1).nextAll().addClass('hidden');
}
self.setEvents();
self.setLinks();
self.isHashIsOnList(location.hash.substring(1));
};
if(self.$element.find('img').length)
self.imageLoaded(callbackImageLoaded);
else
callbackImageLoaded();
},
// Events
scrollToPosition: function (direction){
var position = null,
self = this;
if(self.scrollEl.is(':animated')){
return false;
}
if(direction === 'up' || direction == 'down'){
// Keyboard event
var $next = (direction === 'up') ? self.$current.prev() : self.$current.next();
// Step in the current panel ?
if(self.$step){
if(!self.$current.find('.current-step').length){
self.$step.eq(0).addClass('current-step');
}
var $nextStep = (direction === 'up') ? self.$current.find('.current-step').prev('.step') : self.$current.find('.current-step').next('.step');
if($nextStep.length) {
position = (self.options.mobile) ? $nextStep.position().top + self.$elDatas[self.$current.index()]['data-position'] : $nextStep.position().top + self.$elDatas[self.$current.index()]['data-position'];
}
}
position = position || ((self.$elDatas[$next.index()] === undefined) ? null : self.$elDatas[$next.index()]['data-position']);
if(position !== null){
self.scrollEl.animate({
scrollTop: position
}, self.options.scrollSpeed, self.options.easing);
}
} else if(direction === 'top'){
self.scrollEl.animate({
scrollTop:0
}, self.options.scrollSpeed, self.options.easing);
} else if(direction === 'bottom'){
self.scrollEl.animate({
scrollTop:self.options.bodyHeight
}, self.options.scrollSpeed, self.options.easing);
} else {
var index = $("#"+direction).index(),
speed = Math.abs(self.currentIndex-index) * (this.options.scrollSpeed*4) / self.$liLength;
self.scrollEl.animate({
scrollTop:self.$elDatas[index]['data-position'] || null
}, (speed <= self.options.scrollSpeed) ? self.options.scrollSpeed : speed, this.options.easing);
}
},
scrollEvent: function() {
var self = this,
docTop = self.$document.scrollTop();
if(docTop < self.currentP && self.currentIndex > 0){
// Scroll to top
self._ignoreHashChange = true;
if(self.$current.prev().attr('id'))
self.setHash(self.$current.prev().attr('id'));
self.$current
.removeClass('current')
.css( (self.webkit) ? {'-webkit-transform': 'translateY(0px) translateZ(0)'} : {marginTop: 0} )
.nextAll().addClass('hidden').end()
.prev().addClass('current').removeClass('hidden');
self.setCache();
self.options.prevSlide();
} else if(docTop < (self.currentP + self.currentHeight)){
// Animate the current pannel during the scroll
if(self.webkit)
self.$current.css({'-webkit-transform': 'translateY('+(-(docTop-self.currentP))+'px) translateZ(0)' });
else
self.$current.css({marginTop: -(docTop-self.currentP) });
// If there is a fixed element in the current panel
if(self.$fixedLength){
var dataTop = parseInt(self.$fixed.attr('data-top'), 10);
if(docTop + self.$windowHeight >= self.currentP + self.currentHeight){
self.$fixed.css({
position: 'fixed'
});
} else {
self.$fixed.css({
position: 'absolute',
marginTop: Math.abs(docTop-self.currentP)
});
}
}
// If there is a step element in the current panel
if(self.$stepLength){
$.each(self.$step, function(i,el){
if(($(el).position().top+self.currentP) <= docTop+5 && $(el).position().top + self.currentP + $(el).height() >= docTop+5){
if(!$(el).hasClass('current-step')){
self.$step.removeClass('current-step');
$(el).addClass('current-step');
return false;
}
}
});
}
if(self.parallaxBg){
self.$current.css({
'background-position-y': docTop * self.parallaxBg
});
}
if(self.$fade.length){
self.$fade.css({
'opacity': 1-(docTop/ self.$fade.attr('data-fade'))
});
}
if(self.$slowScroll.length){
self.$slowScroll.css({
'margin-top' : (docTop / self.$slowScroll.attr('data-slow-scroll'))
});
}
} else {
// Scroll bottom
self._ignoreHashChange = true;
if(self.$current.next().attr('id'))
self.setHash(self.$current.next().attr('id'));
self.$current.removeClass('current')
.addClass('hidden')
.next('li').addClass('current').next('li').removeClass('hidden');
self.setCache();
self.options.nextSlide();
}
},
scrollMobileEvent: function() {
var self = this,
docTop = self.$element.scrollTop();
if(docTop+10 < self.currentP && self.currentIndex > 0){
// Scroll to top
self._ignoreHashChange = true;
if(self.$current.prev().attr('id'))
self.setHash(self.$current.prev().attr('id'));
self.$current.removeClass('current').prev().addClass('current');
self.setCache();
self.options.prevSlide();
} else if(docTop+10 < (self.currentP + self.currentHeight)){
// If there is a step element in the current panel
if(self.$stepLength){
$.each(self.$step, function(i,el){
if(($(el).position().top+self.currentP) <= docTop && (($(el).position().top+self.currentP) + $(el).outerHeight()) >= docTop){
if(!$(el).hasClass('current-step')){
self.$step.removeClass('current-step');
$(el).addClass('current-step');
}
}
});
}
} else {
// Scroll bottom
self._ignoreHashChange = true;
if(self.$current.next().attr('id'))
self.setHash(self.$current.next().attr('id'));
self.$current.removeClass('current').next().addClass('current');
self.setCache();
self.options.nextSlide();
}
},
// Setters
setDimensions: function(){
var self = this,
levelHeight = 0,
cover = false,
height = null;
self.$windowHeight = self.$window.height();
this.$li.each(function(index) {
var $self = $(this);
cover = $self.hasClass('cover');
if(cover){
$self.css({height: self.$windowHeight, zIndex: 999-index})
.attr('data-height',self.$windowHeight)
.attr('data-position',levelHeight);
self.$elDatas[$self.index()] = {
'data-height': parseInt(self.$windowHeight,10),
'data-position': parseInt(levelHeight, 10)
};
levelHeight += self.$windowHeight;
} else{
height = ($self.outerHeight() <= self.$windowHeight) ? self.$windowHeight : $self.outerHeight();
$self.css({minHeight: height, zIndex: 999-index})
.attr('data-height',height)
.attr('data-position',levelHeight);
self.$elDatas[$self.index()] = {
'data-height': parseInt(height, 10),
'data-position': parseInt(levelHeight, 10)
};
levelHeight += height;
}
if($self.find('.fixed').length){
var top = $self.find('.fixed').css('top');
$self.find('.fixed').attr('data-top', top);
}
});
if(!this.options.mobile)
this.setBodyHeight();
},
setEvents: function() {
var self = this;
$(window).on('resize', function(){
self.setDimensions();
});
if(self.options.mobile) {
self.$element.on('scroll', function(){
self.scrollMobileEvent();
});
} else {
self.$window.on('scroll', function(){
self.scrollEvent();
});
}
if(self.options.enableKeys) {
self.$document.on('keydown', function(e){
if(e.keyCode === 38 || e.keyCode === 37) {
self.scrollToPosition('up');
e.preventDefault();
return false;
}
if(e.keyCode === 40 || e.keyCode === 39){
self.scrollToPosition('down');
e.preventDefault();
return false;
}
// Home button
if(e.keyCode === 36){
self.scrollToPosition('top');
e.preventDefault();
return false;
}
// End button
if(e.keyCode === 35){
self.scrollToPosition('bottom');
e.preventDefault();
return false;
}
});
}
if(self.options.scrollButtons){
if(self.options.scrollButtons.up){
self.options.scrollButtons.up.on('click', function(e){
e.preventDefault();
self.scrollToPosition('up');
});
}
if(self.options.scrollButtons.down){
self.options.scrollButtons.down.on('click', function(e){
e.preventDefault();
self.scrollToPosition('down');
});
}
}
if(self.options.curtainLinks){
$(self.options.curtainLinks).on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
if(!self.isHashIsOnList(href.substring(1)) && position)
return false;
var position = self.$elDatas[$(href).index()]['data-position'] || null;
if(position){
self.scrollEl.animate({
scrollTop:position
}, self.options.scrollSpeed, self.options.easing);
}
return false;
});
}
self.$window.on("hashchange", function(event){
if(self._ignoreHashChange === false){
self.isHashIsOnList(location.hash.substring(1));
}
self._ignoreHashChange = false;
});
},
setBodyHeight: function(){
var h = 0;
for (var key in this.$elDatas) {
var obj = this.$elDatas[key];
h += obj['data-height'];
}
this.options.bodyHeight = h;
$('body').height(h);
},
setLinks: function(){
var self = this;
this.$li.each(function() {
var id = $(this).attr('id') || 0;
self.options.linksArray.push(id);
});
},
setHash: function(hash){
// "HARD FIX"
el = $('[href=#'+hash+']');
el.parent().siblings('li').removeClass('active');
el.parent().addClass('active');
if(history.pushState) {
history.pushState(null, null, '#'+hash);
}
else {
location.hash = hash;
}
},
setCache: function(){
var self = this;
self.$current = self.$element.find('.current');
self.$fixed = self.$current.find('.fixed');
self.$fixedLength = self.$fixed.length;
self.$step = self.$current.find('.step');
self.$stepLength = self.$step.length;
self.currentIndex = self.$current.index();
self.currentP = self.$elDatas[self.currentIndex]['data-position'];
self.currentHeight = self.$elDatas[self.currentIndex]['data-height'];
self.parallaxBg = self.$current.attr('data-parallax-background');
self.$fade = self.$current.find('[data-fade]');
self.$slowScroll = self.$current.find('[data-slow-scroll]');
},
// Utils
isHashIsOnList: function(hash){
var self = this;
$.each(self.options.linksArray, function(i,val){
if(val === hash){
self.scrollToPosition(hash);
return false;
}
});
},
readyElement: function(el,callback){
var interval = setInterval(function(){
if(el.length){
callback(el.length);
clearInterval(interval);
}
},60);
},
imageLoaded: function(callback){
var self = this,
elems = self.$element.find('img'),
len = elems.length,
blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
elems.bind('load.imgloaded',function(){
if (--len <= 0 && this.src !== blank || $(this).not(':visible')){
elems.unbind('load.imgloaded');
callback.call(elems,this);
}
}).each(function(){
if (this.complete || this.complete === undefined){
var src = this.src;
this.src = blank;
this.src = src;
}
});
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
</script>
First you would have to tell us how you are trying to select text (mouse, keyboard, touchscreen, etc.)
I bet my bitcoins on keyboard (but I don't have any).
Must be one of those
self.$document.on('keydown', function(e){
...
e.preventDefault();
which don't even document which keys these numbers stand for.
It's e.preventDefault() which prevents the default browser action from being performed.
If you're in Chrome devtools, you can use
monitorEvents(window, 'key')
to make sense of these.
Of course this bit may help a bit:
keyCode: 38
keyIdentifier: "Up"
So the code could be written readably by use of keyIdentifier instead of keyCode.
I don't know how compatible that would be across browsers.
Be warned that keydown keyCode values are different from keypress values (which actually insert real characters). keydown key codes will vary between keyboard layouts and locales.
See http://unixpapa.com/js/key.html for disgust and enlightenment, but mostly disgust.

About javascript showbox,I need some help! online~~

<div id="wrapper">
<button id="ppp">button</button>
<div id="content" style="display:none;"></div>
</div>​
if i click the button,the content will be show(open),
if the content is on show(open),when i click document(except the content),the content will be close.
var $ = function (id){
return !id ? null : document.getElementById(id);
}
var addEventSimple = function(obj, evt, fn) {
if (obj.addEventListener){ // W3C
obj.addEventListener(evt, fn, false);
}else if (obj.attachEvent) // Microsoft
obj.attachEvent('on' + evt, fn);
}
var button = $('ppp'),
content = $('content');
var init = function() {};
init.handleObj = button;
init.showbox = content;
init.flag = false;
init.allowcls = false;
init.open = function () {//open the content
if (this.flag == false) {
this.showbox.style.display = "block";
this.flag = true;
this.allowcls = true;
}
};
init.close = function () { // close the content
if (this.flag && this.allowcls) {
this.showbox.style.display = "none";
this.flag = false;
this.allowcls = false;
}
};
init.load = function() { // button click
//e = e ||window.event;
//e.preventDefault();
if (this.flag) {
this.close();
} else {
this.open();
}
};
init.clickClose = function(e) { // document click
if (!this.allowcls) {
return;
}
e = e ||window.event;
var target = e.target;
if (target === this.showbox) { // button
return;
}
this.close();
};
addEventSimple(button, 'click', function (){
init.load();//the code run here OK
})// error on here,but i don't know why?
addEventSimple(document, 'click', function (e){
init.clickClose(e);
})
code in here :http://jsfiddle.net/DCty3/
To toggle element display, you can use function like this:
function toggleDisplay(id) {
var elem = document.getElementById(id);
elem.style.display = (elem.style.display != 'none' ? 'none' : '');
}
There is unlimited id toggle script too:
function toggle() {
for ( var i=0; i < arguments.length; i++ ) {
var elem = document.getElementById(id);
elem.style.display = (elem.style.display != 'none' ? 'none' : '' );
}
}
With jQuery it will be just:
function toggleDisplay(id) {
$('#' + id).toggle();
}
I like getting fancy with objects, here is another multifunctional method:
var display = {
show : function() {
for ( i=0; i < arguments.length; i++ ) {
document.getElementById(arguments[i]).style.display = '';
}
},
hide : function() {
for ( i=0; i < arguments.length; i++ ) {
document.getElementById(arguments[i]).style.display = 'none';
}
},
toggle : function() {
for ( i=0; i < arguments.length; i++ ) {
var elem = document.getElementById(arguments[i]);
elem.style.display = (elem.style.display != 'none' ? 'none' : '' );
}
}
};
To use it, do something like this:
display.show('content','content2','content3');
display.hide('content','content2','content3');
display.toggle('content','content2','content3');
For convenience, you can add another function to enable button:
function toggleDisplayButton(bId, cId) {
document.getElementById(bId).onclick = (function() {
toggleDisplay(cId);
});
}
window.onload = (function() {
toggleDisplayButton('ppp','content');
});
To enable function, when user clicks "outside" the box, and it closes, there is used an easy trick, by creating another element in background, that covers all area around:
<div id="wrapper">
<button id="ppp">button</button>
<div id="outerBox" style="display:none;"></div>
<div id="content" style="display:none;">1</div>
</div>
CSS should make your container relative positioned and "trick box", absolutely positioned, with maximum size of screen, and z-indexed under container like this:
#content{width:100px;height:100px;background-color:#efefef;border:1px solid #555555;z-index:56;position:relative;}
#outerBox{width:100%;height:100%;position:absolute;top:0;left:0;z-index:55;}
And make it work like this:
var display = {
toggle : function() {
for ( i=0; i < arguments.length; i++ ) {
var elem = document.getElementById(arguments[i]);
elem.style.display = (elem.style.display != 'none' ? 'none' : '' );
}
}
};
function toggleBox() {
document.getElementById('ppp').onclick = (function() {
display.toggle('content','outerBox');
});
document.getElementById('outerBox').onclick = (function() {
display.toggle('content','outerBox');
});
}
onload = function() {
toggleBox();
}
The result looks like this.
Your question is exactly same as this one:-
Check out this post :-
jQuery on click $(document) - get clicked element
Hope this will help.

Popup window Maximize button

How to enable the maximize and restore button of the popup window using Javascript?
You have to open a popup like this:
window.open('url', 'windowname', 'location=0, status=0, resizable=1, scrollbars=1, width=400, height=400');
The trick is to make the window resizable. Search for the window.open() function documentation.
Using the code I pasted on the bottom, you can emulate these buttons by creating them in your website interface.
To maximise: save the current position with Namespace.outerPositionGet() and size with Namespace.outerSizeGet(), then do Namespace.outerPositionSet({left:0,top:0}) and Namespace.outerSizeSet({width:window.screen.availWidth, height:window.screen.availHeight}).
To restore: just set position and size which were saved when maximising.
var Namespace = (function() {
var N, W, framePosition, frameChrome, setFramePosition, setFrameChrome;
N = {};
W = window;
setFramePosition = function() {
var tmp0;
if (typeof framePosition !== 'undefined') {
return;
}
tmp0 = {
top : W.screenTop,
left : W.screenLeft
};
W.moveTo(tmp0.left, tmp0.top);
framePosition = {
top : tmp0.top - W.screenTop,
left : tmp0.left - W.screenLeft
};
W.moveTo(tmp0.left + framePosition.left, tmp0.top + framePosition.top);
};
setFrameChrome = function() {
var tmp0, tmp1;
if (typeof frameChrome !== 'undefined') {
return;
}
tmp0 = N.innerSizeGet();
W.resizeTo(tmp0.width, tmp0.height);
tmp1 = N.innerSizeGet();
frameChrome = {
width : tmp0.width - tmp1.width,
height : tmp0.height - tmp1.height
};
W.resizeTo(tmp0.width + tmp1.width, tmp0.height + tmp1.height);
};
N.outerPositionSet = function(position) {
W.moveTo(position.left, position.top);
};
N.outerPositionGet = function() {
if (typeof W.screenTop !== 'undefined') {
setFramePosition();
N.outerPositionGet = function() {
return {
top : W.screenTop + framePosition.top,
left : W.screenLeft + framePosition.left
};
};
} else if (typeof W.screenY !== 'undefined') {
N.outerPositionGet = function() {
return {
top : W.screenY,
left : W.screenX
};
};
} else {
N.outerPositionGet = function() {
return {
top : 0,
left : 0
};
};
}
return N.outerPositionGet();
};
N.outerSizeSet = function(size) {
W.resizeTo(size.width, size.height);
};
N.outerSizeGet = function() {
if (W.outerWidth) {
N.outerSizeGet = function() {
return {
width : W.outerWidth,
height : W.outerHeight
};
};
} else {
setFrameChrome();
N.outerSizeGet = function() {
var size;
size = N.innerSizeGet();
size.width += frameChrome.width;
size.height += frameChrome.height;
return size;
};
}
return N.outerSizeGet();
};
N.innerSizeSet = function(size) {
setFrameChrome();
N.innerSizeSet = function(size) {
W.resizeTo(size.width + frameChrome.width, size.height + frameChrome.height);
};
N.innerSizeSet(size);
};
N.innerSizeGet = function() {
if (typeof W.innerHeight === 'number') {
N.innerSizeGet = function() {
return {
width : W.innerWidth,
height : W.innerHeight
};
};
return N.innerSizeGet();
}
var isDocumentElementHeightOff, node;
isDocumentElementHeightOff = function() {
var div, r;
div = W.document.createElement('div');
div.style.height = "2500px";
W.document.body.insertBefore(div, W.document.body.firstChild);
r = W.document.documentElement.clientHeight > 2400;
W.document.body.removeChild(div);
return r;
};
if (typeof W.document.clientWidth === 'number') {
node = W.document;
} else if ((W.document.documentElement && W.document.documentElement.clientWidth === 0) || isDocumentElementHeightOff()) {
node = W.document.body;
} else if (W.document.documentElement.clientHeight > 0) {
node = W.document.documentElement;
}
N.innerSizeGet = function() {
return {
width : node.clientWidth,
height : node.clientHeight
};
};
return N.innerSizeGet();
};
return N;
})();
I'm assuming you're talking about the alert popup? This can't be done with standard JavaScript.
You best solution would be to try using some of the many popup solutions that have been developed for the various JavaScript frameworks (e.g. jQuery), and seeing if you can tailor this to your particular use.
try this also. its working for me...
window.open('fileURL','status=1,directories=1,menubar=0,toolbar=0,
scrollbars=1,titlebar=0,dialog=1)
You can't, sorry - at least, not universally. The popup is implementation-dependent and there aren't any standard JavaScript methods for controlling it in the manner you describe.

Categories

Resources