How to link js pages in Titanium? - javascript

I'm a beginner coder whose trying to link my js pages together such that when I click on a button it will open up the window of the other js file. However I keep getting the following error message:
"Message: Uncaught TypeError: object is not a function
[ERROR] : TiExceptionHandler: (main) [0,654] - Source: new Window().open();"
whenever I run my application.
Code for my app.js file:
var NavigationController = require('NavigationController').NavigationController,
ApplicationWindow = require('ui/handheld/android/ApplicationWindow').ApplicationWindow;
//create NavigationController which will drive our simple application
var controller = new NavigationController();
//open initial window
controller.open(new ApplicationWindow(this.controller));
Code for my main/home window: (in ApplicationWindow.js)
//Application Window Component Constructor
exports.ApplicationWindow = function(navController) {
//----------------Main Page-------------------------
var winMainPage = Titanium.UI.createWindow({
title:'Radio',
backgroundColor: 'transparent',
});
.
.
.
//open second window
var CategoryButton = Titanium.UI.createButton({
bottom: 20,
left: 50,
width: 60,
height: 60,
backgroundImage: '/images/category.png',
backgroundSelectedImage:'/images/category.gif',
backgroundDisabledImage: '/images/categoryoff.gif',
backgroundColor: 'transparent'
});
//Action listener
CategoryButton.addEventListener('click', function() {
navController.open(new PlayMusic(navController));
});
//to exit app by clicking return button
winMainPage.addEventListener('androidback', function(e){
var confirmClear = Titanium.UI.createAlertDialog({
message:'Exit App?',
buttonNames: ['Yes','No']
});
confirmClear.show();
confirmClear.addEventListener('click',function(e) {
if (e.index === 0) {
winMainPage.close();
}
});
winMainPage.open();
});
return winMainPage;
}
Code in second window: (in PlayMusic.js)
exports.PlayMusic = function(navController){
var self = Ti.UI.createWindow({
backgroundColor:'#ffffff',
navBarHidden:true,
exitOnClose:true
});
.
.
.
return self;
}
The Navigation controller window: (NavigationController.js)
exports.NavigationController = function() {
this.windowStack = [];
};
exports.NavigationController.prototype.open = function(/*Ti.UI.Window*/windowToOpen) {
//add the window to the stack of windows managed by the controller
this.windowStack.push(windowToOpen);
//grab a copy of the current nav controller for use in the callback
var that = this;
windowToOpen.addEventListener('close', function() {
that.windowStack.pop();
});
//hack - setting this property ensures the window is "heavyweight" (associated with an Android activity)
windowToOpen.navBarHidden = windowToOpen.navBarHidden || false;
//This is the first window
if(this.windowStack.length === 1) {
if(Ti.Platform.osname === 'android') {
windowToOpen.exitOnClose = true;
windowToOpen.open();
} else {
this.navGroup = Ti.UI.iPhone.createNavigationGroup({
window : windowToOpen
});
var containerWindow = Ti.UI.createWindow();
containerWindow.add(this.navGroup);
containerWindow.open();
}
}
//All subsequent windows
else {
if(Ti.Platform.osname === 'android') {
windowToOpen.open();
} else {
this.navGroup.open(windowToOpen);
}
}
};
//go back to the initial window of the NavigationController
exports.NavigationController.prototype.home = function() {
//store a copy of all the current windows on the stack
var windows = this.windowStack.concat([]);
for(var i = 1, l = windows.length; i < l; i++) {
(this.navGroup) ? this.navGroup.close(windows[i]) : windows[i].close();
}
this.windowStack = [this.windowStack[0]]; //reset stack
};
Sorry if the way I present my question is unclear. Can anyone please tell me where I've gone wrong? Thanks in advance :)

Pay close attention to your error message:
Message: Uncaught TypeError: object is not a function [ERROR] : TiExceptionHandler: (main) [0,654] - Source: new Window().open();
It looks like you you might be defining Window as an object somewhere and not as a function. Your shared code does not currently show the declaration of Window, however, based on your error message I would say that checking its type is a good place to start debugging. If you could post the declaration of Window it would be much easier to help you :)

Related

Partial view remains active after close

I have a view in which I have a kendo-grid, in this grid there is a button to open a detail window. When the button is pressed the detail window opens which is a kendo-window which renders a partial view. When I close the kendo-window I destroy it and set it to null. However I have a JavaScript function on both my view and my partial view that catches the input of a scanner. If I scan while the window with the partial view is open the function on the view does nothing, however when I close the partial view the JavaScript function on the partial view still catches my scans and it tries to process the scan for both pages at once. How can I make sure the partial view is really closed so that it doesn't catch my scan input (preferably with JavaScript).
Partial view action method:
public ActionResult GetKendoWindow(int ID, int PID)
{
//fill and return partial view locationswindow
ViewBag.ID = ID;
ViewBag.PID = PID;
IEnumerable<BinLocationItemModel> model = dbLogic.getItemLocations(PID, ID);
return PartialView("_PartialViewLocation", model);
}
Kendo-window:
function showDetails(e) {
e.preventDefault();
if (wnd) {
wnd.close();
}
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wndOpen = 1;
$("#detcont").append("<div id='Details'></div>");
wnd = $("#Details").kendoWindow({
width: "60%",
height: "60%",
actions: ["Minimize", "Maximize", "Close"],
title: "Location Data for: " + dataItem.ArticleID,
content: {
url: "GetKendoWindow",
type: "GET",
data: { ID: dataItem.LineNum, PID: dataItem.PickID }
},
close: function (e) {
wnd.destroy();
wnd = null;
setWindowInactive();
}
}).data("kendoWindow");
wnd.center().open();
}
function setWindowInactive(e) {
wndOpen = 0;
}
Partial View JS:
<script type="text/javascript">
//Scanner opvangen
$(document).ready(function () {
if ($('#ItemLocGrid') != null) {
var pressed = false;
var chars = [];
var grid = $('#ItemLocGrid').data('kendoGrid');
var dataitem = grid.dataItem(grid.select());
$(window).keypress(function (e) {
if (e.which >= 48 && e.which <= 57) {
if (chars.length < 3) {
// do nothing
} else {
$('.focus :input').focus();
}
chars.push(String.fromCharCode(e.which));
}
if (pressed == false) {
setTimeout(function () {
if (chars.length >= 5) {
var barcode = chars.join("");
document.getElementById("txtBarcodes").value = barcode;
$('.focus :input').submit();
}
chars = [];
pressed = false;
document.getElementById("txtBarcodes").value = "";
}, 200);
}
pressed = true;
});
}
});
$('#txtBarcodes').submit(function (e) {
var grid = $("#ItemLocGrid").data("kendoGrid");
var dataSource = $("#ItemLocGrid").data("kendoGrid").dataSource;
var allData = grid.dataSource.data();
var code = this.value;
var notification = $("#notification").data("kendoNotification");
console.log("Nothing to see here");
})
Empty your html inside Details div:
close: function (e) {
. . .
$("#Details").html("");
. . .
}
What is return PartialView("_PartialViewLocation", model); doing, is just returning generated html, from your partial view.
UPDATE
The real problem here is, that you should avoid referencing any scripts in partials. So you need to define a section somewhere in your Layout, for example just before the closing </body>, which will allow views (not partial) to include some custom scripts. Then in the view (not partial) you can override this section to include custom scripts:
#section scripts {
<script src="#Url.Content("~/Scripts/Custom.js")" type="text/javascript"></script>
}
It wasn't exactly like SeM mentioned but his code gave me the idea which fixed it. What I did was put my JavaScript code from my partial view into my view(instead of the layout), I didn't realize my view would be able to read a kendo-grid without actually containing it in its code but it actually can. After that it was just a matter of checking if the window is open and processing a scan for either the partial view or the view.

UIkit tabs and switcher do not work after partial refresh

Ok, this is a bit special. We are using UIkit in our XPages application. We also use the tabs and switcher component (http://getuikit.com/docs/tab.html and http://getuikit.com/docs/switcher.html).
They work fine until we do a partial refresh of the page. The reason is that those components are initiliazed only once after the pages is loaded. This happens directly in the lib we bind to the page - no own init script etc.
After the refresh I must re-init the whole stuff - but I am not familiar with the syntax or even the possibilities.
I searched the UIkit lib though and found something like this:
(function(UI) {
"use strict";
UI.component('tab', {
defaults: {
'target' : '>li:not(.uk-tab-responsive, .uk-disabled)',
'connect' : false,
'active' : 0,
'animation' : false,
'duration' : 200
},
boot: function() {
// init code
UI.ready(function(context) {
UI.$("[data-uk-tab]", context).each(function() {
var tab = UI.$(this);
if (!tab.data("tab")) {
var obj = UI.tab(tab, UI.Utils.options(tab.attr("data-uk-tab")));
}
});
});
},
init: function() {
var $this = this;
this.current = false;
this.on("click.uikit.tab", this.options.target, function(e) {
e.preventDefault();
if ($this.switcher && $this.switcher.animating) {
return;
}
var current = $this.find($this.options.target).not(this);
current.removeClass("uk-active").blur();
$this.trigger("change.uk.tab", [UI.$(this).addClass("uk-active"), $this.current]);
$this.current = UI.$(this);
// Update ARIA
if (!$this.options.connect) {
current.attr('aria-expanded', 'false');
UI.$(this).attr('aria-expanded', 'true');
}
});
if (this.options.connect) {
this.connect = UI.$(this.options.connect);
}
// init responsive tab
this.responsivetab = UI.$('<li class="uk-tab-responsive uk-active"><a></a></li>').append('<div class="uk-dropdown uk-dropdown-small"><ul class="uk-nav uk-nav-dropdown"></ul><div>');
this.responsivetab.dropdown = this.responsivetab.find('.uk-dropdown');
this.responsivetab.lst = this.responsivetab.dropdown.find('ul');
this.responsivetab.caption = this.responsivetab.find('a:first');
if (this.element.hasClass("uk-tab-bottom")) this.responsivetab.dropdown.addClass("uk-dropdown-up");
// handle click
this.responsivetab.lst.on('click.uikit.tab', 'a', function(e) {
e.preventDefault();
e.stopPropagation();
var link = UI.$(this);
$this.element.children('li:not(.uk-tab-responsive)').eq(link.data('index')).trigger('click');
});
this.on('show.uk.switcher change.uk.tab', function(e, tab) {
$this.responsivetab.caption.html(tab.text());
});
this.element.append(this.responsivetab);
// init UIkit components
if (this.options.connect) {
this.switcher = UI.switcher(this.element, {
"toggle" : ">li:not(.uk-tab-responsive)",
"connect" : this.options.connect,
"active" : this.options.active,
"animation" : this.options.animation,
"duration" : this.options.duration
});
}
UI.dropdown(this.responsivetab, {"mode": "click"});
// init
$this.trigger("change.uk.tab", [this.element.find(this.options.target).filter('.uk-active')]);
this.check();
UI.$win.on('resize orientationchange', UI.Utils.debounce(function(){
if ($this.element.is(":visible")) $this.check();
}, 100));
this.on('display.uk.check', function(){
if ($this.element.is(":visible")) $this.check();
});
},
check: function() {
var children = this.element.children('li:not(.uk-tab-responsive)').removeClass('uk-hidden');
if (!children.length) return;
var top = (children.eq(0).offset().top + Math.ceil(children.eq(0).height()/2)),
doresponsive = false,
item, link;
this.responsivetab.lst.empty();
children.each(function(){
if (UI.$(this).offset().top > top) {
doresponsive = true;
}
});
if (doresponsive) {
for (var i = 0; i < children.length; i++) {
item = UI.$(children.eq(i));
link = item.find('a');
if (item.css('float') != 'none' && !item.attr('uk-dropdown')) {
item.addClass('uk-hidden');
if (!item.hasClass('uk-disabled')) {
this.responsivetab.lst.append('<li>'+link.html()+'</li>');
}
}
}
}
this.responsivetab[this.responsivetab.lst.children('li').length ? 'removeClass':'addClass']('uk-hidden');
}
});
})(UIkit);
Similar code is created for the connected switcher component.
You can see a demo of my problem here: http://notesx.net/customrenderer.nsf/demo.xsp
Source code here: https://github.com/zeromancer1972/CustomRendererDemo/blob/master/ODP/XPages/demo.xsp
As this is part of the library itself I'd like to find a way to call this from outside the library.
Any ideas are highly appreciated!
Newer versions of uikit have an init method, upgrade and call it from the onComplete event of the combo box.
<xp:comboBox
id="comboBox1">
<xp:selectItems>
<xp:this.value><![CDATA[#{javascript:return ["value 1", "value 2"];}]]></xp:this.value>
</xp:selectItems>
<xp:eventHandler
event="onchange"
submit="true"
refreshMode="partial"
refreshId="page"
onComplete="$.UIkit.init();">
</xp:eventHandler>
</xp:comboBox>

Not able to turn off webcam

I've written a script that successfully activates the user's webcam but throws an error when I try to stop or pause the stream.
I've built a prototype for multi-part single page webapp that requires the user to activate then deactivate their webcam. this version of the prototype doesn't actually capture and store webcam images and it's especially important that the user is able to deactivate the camera so that they don't feel like they're under surveillance.
Below are is my script, which uses a webRTC feature detection lib called compatibility. the line $video.pause() causes the following error
"Uncaught TypeError: undefined is not a function" in Chrome 36.x
while typing "$video" in devtools nad hitting return gives me this
[​​] but doing $video[0].pause() gives me the same error message as above.
I was thinking that doing something like window.URL.revokeObjectURL(stream) -- in my case compatibility.URL.revokeObjectURL(stream) -- was the way to go but wanted to get some advise before diving into that
// get it
var smoother = new Smoother(0.85, [0, 0, 0, 0, 0]),
$video = $("#v"),
$local_media = null;
webcam_capture = function(x){
try {
compatibility.getUserMedia({video: true}, function(stream) {
try {
$video.attr('src', compatibility.URL.createObjectURL(stream));
} catch (error) {
$video.attr(src, stream);
}
$('.camera_prompt').removeClass('show')
}, function (error) {
alert("WebRTC not available");
});
} catch (error) {
console.log(error);
}
}
webcam_capture();
// warn - prompt permissions after 6 seconds
capture_error = setTimeout(function(){
typeof $video.attr('src') == "undefined" ?
$('.camera_prompt').addClass('show') :
clearTimeout(capture_error);
},3000)
start_card_capture = function(x){
// open capture sesh
OAO.card_capture_status = true;
// get id of input to focus and class
var id = 'capture_' + x;
$('input#' + id).addClass('focused');
// UI fade in
$('#v, .notification, button.capture').fadeIn();
}
end_card_capture = function(x){
// close capture sesh
OAO.card_capture_status = false;
// UI fade out
$('#v, .notification, button.capture').fadeOut('visible');
}
capture_notify = function(x){
$('#card_capture_form').find('.notification').find('div').text(x)
}
$('.capture').on('click', function(e){
// determine input
var $f = $(this).parent('form')
$i = $f.find('input.focused');
// check input and update the associated label's icon
$i.prop('checked', true).removeClass('focused');
$i.next('label').addClass('captured');
// close UI
if($f.find('label.captured').length < 2){
end_card_capture(e)
}
if($f.find('label.captured').length == 2){
$video.pause();
OAO.sectional_transition('#funding',{y: '0%'}, 1400,100, $(this).parents('section'), { y: '-250%' }, 1000, 100 );
OAO.step = 2;
OAO.progress_bar(OAO.step)
$('#progress_bar_container').removeClass('hidden');
}
});
$('.capture_front, .capture_back').on('click', function(){
// determine which side
$(this).hasClass('capture_front') ?
OAO.card_capture_side = 'front' :
$(this).hasClass('capture_back') ?
OAO.card_capture_side = 'back' :
C('whichsideofthecardamIshooting?');
if(typeof $video.attr('src') !== "undefined"){
// set prop and init capture
capture_notify(OAO.card_capture_side);
start_card_capture(OAO.card_capture_side)
}
});
Thanks in advance for your help

Check if my website is open in another tab

I want to check with JavaScript if the user has already opened my website in another tab in their browser.
It seems I cannot do that with pagevisibility...
The only way I see is to use WebSocket based on a session cookie, and check if the client has more than one socket. But by this way, from current tab, I have to ask my server if this user has a tab opened right next to their current browser tab. It is a little far-fetched!
Maybe with localstorage?
The shorter version with localStorage and Storage listener
<script type="text/javascript">
// Broadcast that you're opening a page.
localStorage.openpages = Date.now();
var onLocalStorageEvent = function(e){
if(e.key == "openpages"){
// Listen if anybody else is opening the same page!
localStorage.page_available = Date.now();
}
if(e.key == "page_available"){
alert("One more page already open");
}
};
window.addEventListener('storage', onLocalStorageEvent, false);
</script>
Update:
Works on page crash as well.
Stimulate page crash in chrome: chrome://inducebrowsercrashforrealz
Live demo
Using local storage I created a simple demo that should accomplish what your looking to do. Basically, it simply maintains a count of currently opened windows. When the window is closed the unload events fire and remove it from the total window count.
When you first look at it, you may think there's more going on than there really is. Most of it was a shotty attempt to add logic into who was the "main" window, and who should take over as the "main" window as you closed children. (Hence the setTimeout calls to recheck if it should be promoted to a main window) After some head scratching, I decided it would take too much time to implement and was outside the scope of this question. However, if you have two windows open (Main, and Child) and you close the Main, the child will be promoted to a main.
For the most part you should be able to get the general idea of whats going on and use it for your own implementation.
See it all in action here:
http://jsbin.com/mipanuro/1/edit
Oh yeah, to actually see it in action... Open the link in multiple windows. :)
Update:
I've made the necessary changes to have the the local storage maintain the "main" window. As you close tabs child windows can then become promoted to a main window. There are two ways to control the "main" window state through a parameter passed to the constructor of WindowStateManager. This implementation is much nicer than my previous attempt.
JavaScript:
// noprotect
var statusWindow = document.getElementById('status');
(function (win)
{
//Private variables
var _LOCALSTORAGE_KEY = 'WINDOW_VALIDATION';
var RECHECK_WINDOW_DELAY_MS = 100;
var _initialized = false;
var _isMainWindow = false;
var _unloaded = false;
var _windowArray;
var _windowId;
var _isNewWindowPromotedToMain = false;
var _onWindowUpdated;
function WindowStateManager(isNewWindowPromotedToMain, onWindowUpdated)
{
//this.resetWindows();
_onWindowUpdated = onWindowUpdated;
_isNewWindowPromotedToMain = isNewWindowPromotedToMain;
_windowId = Date.now().toString();
bindUnload();
determineWindowState.call(this);
_initialized = true;
_onWindowUpdated.call(this);
}
//Determine the state of the window
//If its a main or child window
function determineWindowState()
{
var self = this;
var _previousState = _isMainWindow;
_windowArray = localStorage.getItem(_LOCALSTORAGE_KEY);
if (_windowArray === null || _windowArray === "NaN")
{
_windowArray = [];
}
else
{
_windowArray = JSON.parse(_windowArray);
}
if (_initialized)
{
//Determine if this window should be promoted
if (_windowArray.length <= 1 ||
(_isNewWindowPromotedToMain ? _windowArray[_windowArray.length - 1] : _windowArray[0]) === _windowId)
{
_isMainWindow = true;
}
else
{
_isMainWindow = false;
}
}
else
{
if (_windowArray.length === 0)
{
_isMainWindow = true;
_windowArray[0] = _windowId;
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(_windowArray));
}
else
{
_isMainWindow = false;
_windowArray.push(_windowId);
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(_windowArray));
}
}
//If the window state has been updated invoke callback
if (_previousState !== _isMainWindow)
{
_onWindowUpdated.call(this);
}
//Perform a recheck of the window on a delay
setTimeout(function()
{
determineWindowState.call(self);
}, RECHECK_WINDOW_DELAY_MS);
}
//Remove the window from the global count
function removeWindow()
{
var __windowArray = JSON.parse(localStorage.getItem(_LOCALSTORAGE_KEY));
for (var i = 0, length = __windowArray.length; i < length; i++)
{
if (__windowArray[i] === _windowId)
{
__windowArray.splice(i, 1);
break;
}
}
//Update the local storage with the new array
localStorage.setItem(_LOCALSTORAGE_KEY, JSON.stringify(__windowArray));
}
//Bind unloading events
function bindUnload()
{
win.addEventListener('beforeunload', function ()
{
if (!_unloaded)
{
removeWindow();
}
});
win.addEventListener('unload', function ()
{
if (!_unloaded)
{
removeWindow();
}
});
}
WindowStateManager.prototype.isMainWindow = function ()
{
return _isMainWindow;
};
WindowStateManager.prototype.resetWindows = function ()
{
localStorage.removeItem(_LOCALSTORAGE_KEY);
};
win.WindowStateManager = WindowStateManager;
})(window);
var WindowStateManager = new WindowStateManager(false, windowUpdated);
function windowUpdated()
{
//"this" is a reference to the WindowStateManager
statusWindow.className = (this.isMainWindow() ? 'main' : 'child');
}
//Resets the count in case something goes wrong in code
//WindowStateManager.resetWindows()
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id='status'>
<span class='mainWindow'>Main Window</span>
<span class='childWindow'>Child Window</span>
</div>
</body>
</html>
CSS:
#status
{
display:table;
width:100%;
height:500px;
border:1px solid black;
}
span
{
vertical-align:middle;
text-align:center;
margin:0 auto;
font-size:50px;
font-family:arial;
color:#ba3fa3;
display:none;
}
#status.main .mainWindow,
#status.child .childWindow
{
display:table-cell;
}
.mainWindow
{
background-color:#22d86e;
}
.childWindow
{
background-color:#70aeff;
}
(2021) You can use BroadcastChannel to communicate between tabs of the same origin.
For example, put the following at the top level of your js code, then test by opening 2 tabs:
const bc = new BroadcastChannel("my-awesome-site");
bc.onmessage = (event) => {
if (event.data === `Am I the first?`) {
bc.postMessage(`No you're not.`);
alert(`Another tab of this site just got opened`);
}
if (event.data === `No you're not.`) {
alert(`An instance of this site is already running`);
}
};
bc.postMessage(`Am I the first?`);
I know it is late, but maybe help someone
This snippet of code, will detect how many tabs are open and how many are active (visible) and if none of tabs is active, it will choose last opened tab, as active one.
This code will handle windows/tab crash too and it will refresh the count at crash.
Because localStorage is not supported on Stack Overflow currently, please test here.
<html>
<body>
Open in several tabs or windows
<div id="holder_element"></div>
<script type="text/javascript">
//localStorage.clear();
manage_crash();
//Create a windows ID for each windows that is oppened
var current_window_id = Date.now() + "";//convert to string
var time_period = 3000;//ms
//Check to see if PageVisibility API is supported or not
var PV_API = page_visibility_API_check();
/************************
** PAGE VISIBILITY API **
*************************/
function page_visibility_API_check ()
{
var page_visibility_API = false;
var visibility_change_handler = false;
if ('hidden' in document)
{
page_visibility_API = 'hidden';
visibility_change_handler = 'visibilitychange';
}
else
{
var prefixes = ['webkit','moz','ms','o'];
//loop over all the known prefixes
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
{
page_visibility_API = prefixes[i] + 'Hidden';
visibility_change_handler = prefixes[i] + 'visibilitychange';
}
}
}
if (!page_visibility_API)
{
//PageVisibility API is not supported in this device
return page_visibility_API;
}
return {"hidden": page_visibility_API, "handler": visibility_change_handler};
}
if (PV_API)
{
document.addEventListener(PV_API.handler, function(){
//console.log("current_window_id", current_window_id, "document[PV_API.hidden]", document[PV_API.hidden]);
if (document[PV_API.hidden])
{
//windows is hidden now
remove_from_active_windows(current_window_id);
//skip_once = true;
}
else
{
//windows is visible now
//add_to_active_windows(current_window_id);
//skip_once = false;
check_current_window_status ();
}
}, false);
}
/********************************************
** ADD CURRENT WINDOW TO main_windows LIST **
*********************************************/
add_to_main_windows_list(current_window_id);
//update active_window to current window
localStorage.active_window = current_window_id;
/**************************************************************************
** REMOVE CURRENT WINDOWS FROM THE main_windows LIST ON CLOSE OR REFRESH **
***************************************************************************/
window.addEventListener('beforeunload', function ()
{
remove_from_main_windows_list(current_window_id);
});
/*****************************
** ADD TO main_windows LIST **
******************************/
function add_to_main_windows_list(window_id)
{
var temp_main_windows_list = get_main_windows_list();
var index = temp_main_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in the list currently
temp_main_windows_list.push(window_id);
}
localStorage.main_windows = temp_main_windows_list.join(",");
return temp_main_windows_list;
}
/**************************
** GET main_windows LIST **
***************************/
function get_main_windows_list()
{
var temp_main_windows_list = [];
if (localStorage.main_windows)
{
temp_main_windows_list = (localStorage.main_windows).split(",");
}
return temp_main_windows_list;
}
/**********************************************
** REMOVE WINDOWS FROM THE main_windows LIST **
***********************************************/
function remove_from_main_windows_list(window_id)
{
var temp_main_windows_list = [];
if (localStorage.main_windows)
{
temp_main_windows_list = (localStorage.main_windows).split(",");
}
var index = temp_main_windows_list.indexOf(window_id);
if (index > -1) {
temp_main_windows_list.splice(index, 1);
}
localStorage.main_windows = temp_main_windows_list.join(",");
//remove from active windows too
remove_from_active_windows(window_id);
return temp_main_windows_list;
}
/**************************
** GET active_windows LIST **
***************************/
function get_active_windows_list()
{
var temp_active_windows_list = [];
if (localStorage.actived_windows)
{
temp_active_windows_list = (localStorage.actived_windows).split(",");
}
return temp_active_windows_list;
}
/*************************************
** REMOVE FROM actived_windows LIST **
**************************************/
function remove_from_active_windows(window_id)
{
var temp_active_windows_list = get_active_windows_list();
var index = temp_active_windows_list.indexOf(window_id);
if (index > -1) {
temp_active_windows_list.splice(index, 1);
}
localStorage.actived_windows = temp_active_windows_list.join(",");
return temp_active_windows_list;
}
/********************************
** ADD TO actived_windows LIST **
*********************************/
function add_to_active_windows(window_id)
{
var temp_active_windows_list = get_active_windows_list();
var index = temp_active_windows_list.indexOf(window_id);
if (index < 0)
{
//this windows is not in active list currently
temp_active_windows_list.push(window_id);
}
localStorage.actived_windows = temp_active_windows_list.join(",");
return temp_active_windows_list;
}
/*****************
** MANAGE CRASH **
******************/
//If the last update didn't happened recently (more than time_period*2)
//we will clear saved localStorage's data and reload the page
function manage_crash()
{
if (localStorage.last_update)
{
if (parseInt(localStorage.last_update) + (time_period * 2) < Date.now())
{
//seems a crash came! who knows!?
//localStorage.clear();
localStorage.removeItem('main_windows');
localStorage.removeItem('actived_windows');
localStorage.removeItem('active_window');
localStorage.removeItem('last_update');
location.reload();
}
}
}
/********************************
** CHECK CURRENT WINDOW STATUS **
*********************************/
function check_current_window_status(test)
{
manage_crash();
if (PV_API)
{
var active_status = "Inactive";
var windows_list = get_main_windows_list();
var active_windows_list = get_active_windows_list();
if (windows_list.indexOf(localStorage.active_window) < 0)
{
//last actived windows is not alive anymore!
//remove_from_main_windows_list(localStorage.active_window);
//set the last added window, as active_window
localStorage.active_window = windows_list[windows_list.length - 1];
}
if (! document[PV_API.hidden])
{
//Window's page is visible
localStorage.active_window = current_window_id;
}
if (localStorage.active_window == current_window_id)
{
active_status = "Active";
}
if (active_status == "Active")
{
active_windows_list = add_to_active_windows(current_window_id);
}
else
{
active_windows_list = remove_from_active_windows(current_window_id);
}
console.log(test, active_windows_list);
var element_holder = document.getElementById("holder_element");
element_holder.insertAdjacentHTML("afterbegin", "<div>"+element_holder.childElementCount+") Current Windows is "+ active_status +" "+active_windows_list.length+" window(s) is visible and active of "+ windows_list.length +" windows</div>");
}
else
{
console.log("PageVisibility API is not supported :(");
//our INACTIVE pages, will remain INACTIVE forever, you need to make some action in this case!
}
localStorage.last_update = Date.now();
}
//check storage continuously
setInterval(function(){
check_current_window_status ();
}, time_period);
//initial check
check_current_window_status ();
</script>
</body>
</html>

Console.log Internet explorer 8 particular case [duplicate]

This question already has answers here:
'console' is undefined error for Internet Explorer
(21 answers)
Closed 8 years ago.
Hi i found the problem in other stackoverflow questions , the problem is i have tried all solutions that should work, but i think im not understanding where and how to implement that fixes..
My problem is console.log in internet explorer throws an error as undefined. I search and found
Console undefined issue in IE8
Internet Explorer: "console is not defined" Error
I try to wrap the code inside the function using a condition like 'if(window.console) '
this dosent work i even try most of the recommended contitions no one work, try to insert the snnipet in the code so it worked, but it dont..
Im obviously not understanding how and where to put does fixes. Sorry for my ignorance. but im in a hurry, need to someone points at my stupidity
Thanks
var jcount = 0;
var scroll_count = 0;
var playflag=1;
var ajxcallimiter=0;
var hp_totalcount=parseInt($("#hp_totalcount").val());
if(hp_totalcount<5)
hp_totalcount=5;
function hlist_slider()
{
if($(".items img").eq(jcount).length != 0 && playflag==1){
firedstyle();
console.log(jcount);
$(".items img").eq(jcount).trigger("mouseover");
if(jcount % 5 === 0 && jcount!=0)
{
console.log('scroll');
api.next();
scroll_count++;
}
jcount++; // add to the counter
if(jcount>hp_totalcount)
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}scroll_count=1;
}
}
}
else if(jcount<hp_totalcount && playflag==1)
{
playflag=0;homepagelist_nextclick();playflag=1;
}
else
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}
scroll_count=1;
}
}
}
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
hlist_slider();
setInterval(hlist_slider,10000);
// provide scrollable API for the action buttons
window.api = root.data("scrollable");
});
function firedstyle()
{
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
var tbtitgoto = $(this).attr("data");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
wrap.find("a").attr("href", tbtitgoto);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
}
function toggle(el){
if(el.className!="play")
{
playflag=0;
el.className="play";
el.src='images/play.png';
//api.pause();
}
else if(el.className=="play")
{
playflag=1;
el.className="pause";
el.src='images/pause.png';
// api.play();
}
return false;
}
function hp_nxtclick()
{
homepagelist_nextclick();
console.log('scroll');
if(api.next()){
scroll_count++;}
}
function homepagelist_nextclick()
{
var hp_totalcount=parseInt($("#hp_totalcount").val());
var hp_count=parseInt($("#hp_count").val());
if(hp_totalcount==0 || hp_count >=hp_totalcount)
return ;
if(ajxcallimiter==1)
return;
else
ajxcallimiter=1;
$.ajax(
{
type: "GET",
url: "<?php echo $makeurl."index/homepageslide/";?>"+hp_count,
success: function(msg)
{
hp_count=parseInt($("#hp_count").val())+parseInt(5);
$("#hp_count").val(hp_count);
$("#hp_list").append(msg);ajxcallimiter=0;
}
});
}
The problem is that the console (developer tool panel) needs to be active on page-load*.
Hit F12, reload your page, and you should get what you're looking for.
*Just to clarify: The developer panel needs to be open prior to window.console being called/tested. I'm assuming your code is being run on-load.
This should work:
if(!window.console || !window.console.log) window.console = {log: function(){}};
This way you will be able to use console.log without producing errors.
In my code, I put this snippet at the top - before any other javascript that might try to use the console loads:
if (window.console == null) {
window.console = {
log: function() {},
warn: function() {},
info: function() {},
error: function() {}
};
}
Or in coffeescript:
if not window.console?
window.console = {
log: () ->
warn: () ->
info: () ->
error: () ->
}
This provides a dummy console for browsers that don't include one.

Categories