Outdated Browser - Only show banner from IE8 and lower. Currently IE9 is included - browser

I want this code to only display outdated browser from IE8 and lower. Currently it also shows a message for IE9, which I want to exclude. I did try to remove the IE9 part of the code from the lowerthan part of the code, but no luck.
I got the code from: https://github.com/burocratik/outdated-browser
/*!--------------------------------------------------------------------
JAVASCRIPT "Outdated Browser"
Version: 1.1.0 - 2014
author: Burocratik
website: http://www.burocratik.com
* #preserve
-----------------------------------------------------------------------*/
var outdatedBrowser = function(options) {
//Variable definition (before ajax)
var outdated = document.getElementById("outdated");
// Default settings
this.defaultOpts = {
bgColor: '#f25648',
color: '#ffffff',
lowerThan: 'transform',
languagePath: '../outdatedbrowser/lang/en.html'
}
if (options) {
//assign css3 property to IE browser version
if(options.lowerThan == 'IE8' || options.lowerThan == 'borderSpacing') {
options.lowerThan = 'borderSpacing';
} else if (options.lowerThan == 'IE9' || options.lowerThan == 'boxShadow') {
options.lowerThan = 'boxShadow';
} else if (options.lowerThan == 'IE10' || options.lowerThan == 'transform' || options.lowerThan == '' || typeof options.lowerThan === "undefined") {
options.lowerThan = 'transform';
} else if (options.lowerThan == 'IE11' || options.lowerThan == 'borderImage') {
options.lowerThan = 'borderImage';
}
//all properties
this.defaultOpts.bgColor = options.bgColor;
this.defaultOpts.color = options.color;
this.defaultOpts.lowerThan = options.lowerThan;
this.defaultOpts.languagePath = options.languagePath;
bkgColor = this.defaultOpts.bgColor;
txtColor = this.defaultOpts.color;
cssProp = this.defaultOpts.lowerThan;
languagePath = this.defaultOpts.languagePath;
} else {
bkgColor = this.defaultOpts.bgColor;
txtColor = this.defaultOpts.color;
cssProp = this.defaultOpts.lowerThan;
languagePath = this.defaultOpts.languagePath;
};//end if options
//Define opacity and fadeIn/fadeOut functions
var done = true;
function function_opacity(opacity_value) {
outdated.style.opacity = opacity_value / 100;
outdated.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
// function function_fade_out(opacity_value) {
// function_opacity(opacity_value);
// if (opacity_value == 1) {
// outdated.style.display = 'none';
// done = true;
// }
// }
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
outdated.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
//check if element has a particular class
// function hasClass(element, cls) {
// return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
// }
var supports = (function() {
var div = document.createElement('div'),
vendors = 'Khtml Ms O Moz Webkit'.split(' '),
len = vendors.length;
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
return true;
}
}
return false;
};
})();
//if browser does not supports css3 property (transform=default), if does > exit all this
if ( !supports(''+ cssProp +'') ) {
if (done && outdated.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x);
};
})(i), i * 8);
}
}
}else{
return;
};//end if
//Check AJAX Options: if languagePath == '' > use no Ajax way, html is needed inside <div id="outdated">
if( languagePath === ' ' || languagePath.length == 0 ){
startStylesAndEvents();
}else{
grabFile(languagePath);
}
//events and colors
function startStylesAndEvents(){
var btnClose = document.getElementById("btnCloseUpdateBrowser");
var btnUpdate = document.getElementById("btnUpdateBrowser");
//check settings attributes
outdated.style.backgroundColor = bkgColor;
//way too hard to put !important on IE6
outdated.style.color = txtColor;
outdated.children[0].style.color = txtColor;
outdated.children[1].style.color = txtColor;
//check settings attributes
btnUpdate.style.color = txtColor;
// btnUpdate.style.borderColor = txtColor;
if (btnUpdate.style.borderColor) btnUpdate.style.borderColor = txtColor;
btnClose.style.color = txtColor;
//close button
btnClose.onmousedown = function() {
outdated.style.display = 'none';
return false;
};
//Override the update button color to match the background color
btnUpdate.onmouseover = function() {
this.style.color = bkgColor;
this.style.backgroundColor = txtColor;
};
btnUpdate.onmouseout = function() {
this.style.color = txtColor;
this.style.backgroundColor = bkgColor;
};
}//end styles and events
// IF AJAX with request ERROR > insert english default
var ajaxEnglishDefault = '<h6>Your browser is out-of-date!</h6>'
+ '<p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" href="http://outdatedbrowser.com/">Update my browser now </a></p>'
+ '<p class="last">×</p>';
//** AJAX FUNCTIONS - Bulletproof Ajax by Jeremy Keith **
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
};//end function
function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
displayResponse(request);
};
request.open("GET", file, true);
request.send(null);
}
return false;
};//end grabFile
function displayResponse(request) {
var insertContentHere = document.getElementById("outdated");
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
insertContentHere.innerHTML = request.responseText;
}else{
insertContentHere.innerHTML = ajaxEnglishDefault;
}
startStylesAndEvents();
}
return false;
};//end displayResponse
////////END of outdatedBrowser function
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Outdated Browser</title>
<meta name="description" content="A time saving tool for developers. It detects outdated browsers and advises users to upgrade to a new version.">
<!-- Styles -->
<link rel="stylesheet" href="../outdatedbrowser/outdatedbrowser.min.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style type="text/css">
body {
font-family: 'Open Sans', sans-serif; text-align: center;
background-color: #fafafa; color: #0a0a0a; line-height: 1.5em;
}
h1{font-size: 2.6em; line-height: 2em;}
h3, h4{line-height: 1em; margin: 2.5em 0 -.4em 0; text-transform: uppercase;}
h3 span, h4 span{text-transform: none;}
p{padding-bottom: 1em;}
p.designBy{position: absolute; bottom: 0; right: 1em; font-size: .8em;}
a {color: #0a0a0a;}
ul{list-style-type: none; padding: 0;}
</style>
</head>
<body>
<!-- ============= YOUR CONTENT ============= -->
<h1>Outdated Browser</h1>
<p>Remember: If you can't see the message, it's a good thing! You are using a modern browser :D</p>
<h3>DEFAULT properties but using jQuery (must support IE6+)</h3>
<p>bgColor: '#f25648', color: '#ffffff', lowerThan: 'transform' (<IE10), languagePath: 'your_path/outdatedbrowser/lang/en.html'</p>
<h3>What does it look like? <span>(it may differ in your tests) </span></h3>
<ul>
<li>IE7 - VISTA</li>
</ul>
<p class="designBy">by Bürocratik</p>
<!-- ============= Outdated Browser ============= -->
<div id="outdated"></div>
<!-- javascript includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="../outdatedbrowser/outdatedbrowser.js"></script>
<!-- plugin call -->
<script>
//USING jQuery
$(document).ready(function() {
outdatedBrowser({
bgColor: '#f25648',
color: '#ffffff',
lowerThan: 'transform',
languagePath: '../outdatedbrowser/lang/en.html'
})
})
console.log(outdatedBrowser);
</script>
</script>
</body>
</html>

Related

how to turn off sliding responsive menu in wordpress responsive select menu plugin?

I am using WP Responsive Select Menu plugin in wordpress and I have responsive menu while watching the website in the mobile devices.
In my IOS based phone, the responsive menu opens automatically when I scroll the screen to left (and sometimes also when I scroll down).
My .js file is as follows:
`
// Start Code
jQuery(document).ready(function( $ ) {
var bar = $('#wpresmenu_bar'), //top bar that shows/hides the menu
bar_height = bar.outerHeight(true), //the bar height
from_width = wpresmenu.from_width,
menu = $('#wpresmenu_menu'), //the menu div
menu_ul = $('#wpresmenu_menu_ul'), //the menu ul
menu_a = menu.find('a'), //single menu link
body = $('body'),
html = $('html'),
animation_speed = 300,
ab = $('#wpadminbar'),
menu_enabled = (bar.length > 0 && menu.length > 0)? true : false,
menu_width = menu.width(),
target_height = (window.innerHeight < body.height())? body.height() : window.innerHeight,
target_width = (window.innerWidth < body.width())? body.width() : window.innerWidth;
if(menu_enabled) {
menu_ul.find('li').first().css({'border-top':'none'});
$(document).mouseup(function (e) {
if ( !menu.is(e.target) && menu.has( e.target ).length === 0) {
if(menu.is(':visible') && (!menu.hasClass('top'))) {
$.sidr('close', 'wpresmenu_menu');
}
}
});
//ENABLE NESTING
//add arrow element to the parent li items and chide its child uls
menu.find('ul.sub-menu').each(function() {
var sub_ul = $(this),
parent_a = sub_ul.prev('a'),
parent_li = parent_a.parent('li').first();
parent_a.addClass('wpresmenu_parent_item');
parent_li.addClass('wpresmenu_parent_item_li');
var expand = parent_a.before('<span class="wpresmenu_icon wpresmenu_icon_par icon_default"></span> ').find('.wpresmenu_icon_par');
sub_ul.hide();
});
//adjust the a width on parent uls so it fits nicely with th eicon elemnt
function adjust_expandable_items() {
$('.wpresmenu_parent_item_li').each(function() {
var t = $(this),
main_ul_width = 0,
icon = t.find('.wpresmenu_icon_par').first(),
link = t.find('a.wpresmenu_parent_item').first();
if(menu.hasClass('top')) {
main_ul_width = window.innerWidth;
} else {
main_ul_width = menu_ul.innerWidth();
}
if(t.find('.wpresmenu_clear').length == 0) link.after('<br class="wpresmenu_clear"/>');
});
}
adjust_expandable_items();
//expand / collapse action (SUBLEVELS)
$('.wpresmenu_icon_par').on('click',function() {
var t = $(this),
//child_ul = t.next('a').next('ul');
child_ul = t.parent('li').find('ul.sub-menu').first();
child_ul.slideToggle(300);
t.toggleClass('wpresmenu_par_opened');
t.parent('li').first().toggleClass('wpresmenu_no_border_bottom');
});
//helper - close all submenus when menu is hiding
function close_sub_uls() {
menu.find('ul.sub-menu').each(function() {
var ul = $(this),
icon = ul.parent('li').find('.wpresmenu_icon_par'),
li = ul.parent('li');
if(ul.is(':visible')) ul.slideUp(300);
icon.removeClass('wpresmenu_par_opened');
li.removeClass('wpresmenu_no_border_bottom');
});
}
//fix the scaling issue by adding/replacing viewport metatag
var mt = $('meta[name=viewport]');
mt = mt.length ? mt : $('<meta name="viewport" />').appendTo('head');
if(wpresmenu.zooming == 'no') {
mt.attr('content', 'user-scalable=no, width=device-width, maximum-scale=1, minimum-scale=1');
} else {
mt.attr('content', 'user-scalable=yes, width=device-width, initial-scale=1.0, minimum-scale=1');
}
//Additional fixes on change device orientation
if( $.browser.mozilla ) {
screen.addEventListener("orientationchange", function() {updateOrientation()}); //firefox
} else if( window.addEventListener ) {
window.addEventListener('orientationchange', updateOrientation, false);
}
else {
window.attachEvent( "orientationchange" );
}
function updateOrientation() {
window.scrollBy(1,1);
window.scrollBy(-1,-1);
menu_width = menu.width();
//update the page posion for left menu
if(menu.is(':visible') && menu.hasClass('left')) {
body.css({'left':menu_width});
body.scrollLeft(0);
}
}
//apply the SIDR for the left/right menu
if(menu.hasClass('left') || menu.hasClass('right')) {
//appy sidr
var hor_pos = (menu.hasClass('left'))? 'left' : 'right';
bar.sidr({
name:'wpresmenu_menu',
side: hor_pos,
speed: animation_speed,
onOpen: function(){ bar.addClass('menu_is_opened'); },
onClose: function(){ bar.removeClass('menu_is_opened'); close_sub_uls(); }
});
//when link is clicked - hide the menu first and then change location to new page
menu_a.on('click', function(e) {
$.sidr('close', 'wpresmenu_menu');
});
if( wpresmenu.swipe != 'no' ) {
$('body').touchwipe({
wipeLeft: function() {
// Close
$.sidr('close', 'wpresmenu_menu');
},
wipeRight: function() {
// Open
$.sidr('open', 'wpresmenu_menu');
},
min_move_x: 60,
min_move_y: 60,
preventDefaultEvents: false
});
}
$(window).resize(function(){
target_width = (window.innerWidth < body.width())? body.width() : window.innerWidth;
if(target_width > from_width && menu.is(':visible')) {
$.sidr('close', 'wpresmenu_menu');
}
});
} else if(menu.hasClass('top')) { //The top positioned menu
body.prepend(menu);
//show / hide the menu
bar.on('click', function(e) {
//scroll window top
$("html, body").animate({ scrollTop: 0 }, animation_speed);
close_sub_uls();
menu.stop(true, false).slideToggle(animation_speed);
});
//when link is clicked - hide the menu first and then change location to new page
menu_a.on('click', function(e) {
e.preventDefault();
var url = $(this).attr('href');
menu.slideUp(animation_speed,function() {
//go to the url from the link
window.location.href = url;
});
});
$(window).resize(function(){
target_width = (window.innerWidth < body.width())? body.width() : window.innerWidth;
if(target_width > from_width && menu.is(':visible')) {
close_sub_uls();
menu.slideUp(animation_speed, function() {});
}
});
} //end if class left / top /right
} //end if menu enabled
}); `
I don't want the menu to load on sliding the screen to left or right. Any idea how to do that??
I have figured it out.
Commenting out the following code stops it.
if( wpresmenu.swipe != 'no' ) {
$('body').touchwipe({
wipeLeft: function() {
// Close
$.sidr('close', 'wpresmenu_menu');
},
wipeRight: function() {
// Open
$.sidr('open', 'wpresmenu_menu');
},
min_move_x: 60,
min_move_y: 60,
preventDefaultEvents: false
});
}
:)

Create a new Webshop Parameter

I am very new to hybris e-commerce software and trying to learn with the help of wiki documents provided with it.I am trying to create a new Webshop parameter with three options so I can choose any one of then by HMC. I have changed the items.xml and created a enum and a new attribute in Basestore but on HMC name of new parameter is not proper its taking qualifier name appended with "[" can anyone suggest why it is happening and how to define name of new parameter.
1) myextension-items.xml
<itemtype code="MyType" extends="BaseType">
<attributes>
<attribute qualifier="attr1" type="java.lang.String">
<persistence type="property" />
</attribute>
</attributes>
</itemtype>
2) localization\myextension-locales_en.properties (or other: _fr, _de, etc)
type.MyType.name=My Type name
type.MyType.description=My Type description
type.MyType.attr1.name=Attribute 1 name
type.MyType.attr1.description=Attribute 1 description
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
table {
border: 1px solid black;
}
p {
position: relative;
left: 60px;
}
</style>
</head>
<body>
<h2>Pizzahut</h2>
<div id="container">
<label>Megnevezés</label><br>
<input id='Megnevezes' type="text"><br>
<label>Pizza mérete</label><br>
<select id="pizzameret" name="pizzameret" >
<option>S</option>
<option>L</option>
<option>XL</option>
</select><br>
<label>Egységár</label><br>
<input id='Egysegar' type="number"><br>
<label>Fénykép</label><br>
<input id='fenykep' type="text"><br>
<button onclick="pizzaHozzaad()">Feltöltés</button>
<!--fügvényhívás-->
</div>
<br>
<br>
<br>
<div id="tablaParent">
</div>
<br>
<br>
<br>
<div id="kosarTartalma">
<p>Kosár tartalma</p>
<table>
<thead>
<tr>
<th>id</th>
<th>pizzameret</th>
<th>megnevezes</th>
<th>egysegar</th>
<th>fenykep</th>
</tr>
<!--
<tr>
<th><input id="idSzuro" /></th>
<th>
<select id="pizzameretSzuro">
<option>S</option>
<option>L</option>
<option>XL</option>
</select>
</th>
<th><input id="megnevezesSzuro" /></th>
<th><input id="egysegarSzuro" /></th>
<th><input id="fenykepSzuro" /></th>
</tr>
-->
</thead>
<tbody id="kosarBody">
</tbody>
</table>
</div>
<script type="text/javascript" , src="pizza.js"></script>
<script type="text/javascript" , src="webshoplogika.js"></script>
</body>
</html>
function Pizza(id,megnevezes,egysegar,fenykep,pizzameret)
{
this.id=id;
this.pizzameret=pizzameret;
this.megnevezes = megnevezes;
this.egysegar = egysegar;
this.fenykep = fenykep ;
}
"use strict"
var termekek = [];
var tablazatParent = "";
var kosar = [];
var novekvo = true;
termekek.push(new Pizza(1, "pizza1", 600, "kamu.jpg","xl"));
termekek.push(new Pizza(2, "pizza2", 100, "kamu.jpg","xl"));
termekek.push(new Pizza(3, "pizza3", 200, "kamu.jpg","xl"));
termekek.push(new Pizza(4, "pizza4", 4000, "kamu.jpg","xl"));
termekek.push(new Pizza(5, "pizza5", 5000, "kamu.jpg","xl"));
termekek.push(new Pizza(6, "pizza5", 12000, "kamu.jpg","xl"));
var pizzameret = document.getElementById("pizzameret");
var Megnevezes = document.getElementById("Megnevezes");
var Egysegar = document.getElementById("Egysegar");
var fenykep = document.getElementById("fenykep");
var id = 6;
window.addEventListener('load', Window_Load_Handler, false);
function Window_Load_Handler() {
tablazatParent=document.getElementById("tablaParent");
tablazatRajzoloFuggveny(termekek);
}
function pizzaHozzaad() {
id++;
var pizzaNev = Megnevezes.value;
var pizzaAr = Egysegar.value;
var fenykepURL = fenykep.value;
var ujPizza = new Pizza(id, pizzaNev, pizzaAr, fenykepURL);
termekek.push(ujPizza);
console.log(ujPizza);
tablazatFrissites();
}
function tablazatRajzoloFuggveny(inputArray) { /* ugy kell meghivni, masik gombnyomasra,hogy at kell adnunk neki paratmeterkent egy tombot,
amivel megmondjuk melyik tombbol szeretnenk tablazatot csinalni */
var tablazat = document.createElement('table')
tablazat.setAttribute("border", "true"); /* a tablazatot hozza letre */
var sor = document.createElement('TR'); /* a sort hozza letre */
for (var k in inputArray[0]) {
var cella = document.createElement('TH') /*create elementtel keszitettunk egy header cellat */
cella.innerText = k;
cella.addEventListener('click', rendezd , false);
sor.appendChild(cella); /* cellat felakasztja a sorra */
}
var btnCella = document.createElement('TH'); // gombot kreálunk
btnCella.innerText = "Kosárba";
sor.appendChild(btnCella);
tablazat.appendChild(sor);
var btnCella = document.createElement('TH'); // gombot kreálunk
btnCella.innerText = "Törlés";
sor.appendChild(btnCella);
tablazat.appendChild(sor);
var sor = document.createElement('TR');
for (var k in inputArray[0]) {
var cella = document.createElement('TH') /*create elementtel keszitettunk egy header cellat */
if (k == "pizzameret") {
var szuro = document.createElement('SELECT');
szuro.id= k
var optionXL = document.createElement('OPTION')
optionXL.text = 'XL'
optionXL.value = 'XL'
var optionL = document.createElement('OPTION')
optionL.text = 'L'
optionL.value = 'L'
var optionS = document.createElement('OPTION')
optionS.text = 'S'
optionS.value = 'S'
szuro.appendChild(optionXL)
szuro.appendChild(optionL)
szuro.appendChild(optionS)
szuro.addEventListener('change', szurd , true);
cella.appendChild(szuro)
} else {
var szuro = document.createElement('INPUT');
szuro.id= k
szuro.addEventListener('focusout', szurd , true);
cella.appendChild(szuro)
}
sor.appendChild(cella); /* cellat felakasztja a sorra */
}
tablazat.appendChild(sor); /* sort felakasztja a tablara */
document.body.appendChild(tablazat);
for (var i = 0; i < inputArray.length; i++) {
var sor = document.createElement('TR'); /* a sort hozza letre */
for (var k in inputArray[i]) {
var cella = document.createElement('TD') /*create elementtel keszitettunk egy header cellat */
cella.innerText = inputArray[i][k]; /*aktualis auto k kulcsai, value-jat olvassa be */
sor.appendChild(cella);
}
var btnCella = document.createElement('TD'); // gombot kreálunk
btnCella.innerHTML = "";
sor.appendChild(btnCella);
tablazat.appendChild(sor);
tablazat.appendChild(sor);
var kosarbaBtn = document.createElement('input');
kosarbaBtn.setAttribute('type', 'button');
kosarbaBtn.setAttribute('value', 'Kosárba');
kosarbaBtn.setAttribute('termekID',inputArray[i].id );
kosarbaBtn.addEventListener('click', Kosarba_Click_Handler , false);
var torolBtn = document.createElement('input');
torolBtn.setAttribute('type', 'button');
torolBtn.setAttribute('value', 'Torlés');
torolBtn.setAttribute('termekID',inputArray[i].id );
torolBtn.addEventListener('click', toroldasort , false);
btnCella.appendChild( kosarbaBtn);
var btnCella = document.createElement('TD'); // gombot kreálunk
btnCella.appendChild( torolBtn);
sor.appendChild(btnCella);
tablazat.appendChild(sor);
tablazat.appendChild(sor);
}
tablazatParent.appendChild(tablazat);
}
function toroldasort(){
var btn = event.target;
var id = btn.getAttribute('termekID');
console.log("termek id:" + btn.getAttribute('termekID'));
for( var i = 0; i < termekek.length; i++){
if ( termekek[i].id == id ) {
console.log("lofasz");
termekek.splice(i, 1);
break;
}
}
tablazatFrissites();
}
function tablazatFrissites() {
//var tablazatParent=getElementById('tablazat'); //feltetteük a tetejére
var nodeTermekLista = document.querySelector('#tablaParent');
nodeTermekLista.innerText='';
tablazatRajzoloFuggveny(termekek);
}
function rendezd() {
var header = event.target
var attr = header.innerText
console.log(attr); // ha igy mukodik akkor nem is kell gomb se input type legyen stb. próba cseresznye
// fasza, megy, akkor folytassuk, ugye rendezni kell a szerint az attributum szerint amit megnyomtunk
// ez most csökkenő sorrendbe rendezi az oszlopokat (már amennyi értelme van ennek stringek esetében)
termekek.sort(function(a, b){
//console.log(a[attr])
// na mindegy, eddigiek alapján a ciklussal láttuk h kell kiszedni egy ojjektum mezejét
// á faszom, kell erre legyen vmi egyszerű megoldás
console.log(a[attr] +' '+ b[attr])
// ez ugye számokra jó de stringekre nem
if (novekvo) {
if (a[attr] < b[attr])
return -1;
if (a[attr] > b[attr])
return 1;
} else {
if (a[attr] < b[attr])
return 1;
if (a[attr] > b[attr])
return -1;
}
return 0;
})
novekvo = !novekvo
console.log(novekvo)
// https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value
// fasza, műxik, látszik a termékeken h most csökkenő sorrendben vannak
// ja igen és még ki kell rajzolni
tablazatFrissites()
}
function szurd() {
var szurtTermekek = []
var asd = event.target
console.log(termekek)
for (var i = 0; i < termekek.length; i++) {
console.log(termekek[i][asd.id]+' '+asd.value)
if (termekek[i][asd.id] == asd.value) {
console.log(termekek[i][asd.id])
szurtTermekek.push(termekek[i])
}
}
console.log(szurtTermekek)
if (szurtTermekek.length > 0) {
var nodeTermekLista = document.querySelector('#tablaParent');
nodeTermekLista.innerText='';
tablazatRajzoloFuggveny(szurtTermekek)
}
}
function Kosarba_Click_Handler() {
var btn = event.target;
var id = btn.getAttribute('termekID');
console.log("kosarba termek id:" + btn.getAttribute('termekID'));
var valasztottTermek;
for( var i = 0; i < termekek.length; i++){
if ( termekek[i].id == id ) {
valasztottTermek = termekek[i];
console.log("kosarba!!");
break;
}
}
var kosarLista = document.querySelector('#kosarBody');
var sor = document.createElement('TR');
for (var k in valasztottTermek) {
var cella = document.createElement('TD')
cella.innerText = valasztottTermek[k];
sor.appendChild(cella);
}
kosarLista.appendChild(sor);
}

Grunt insert string after pattern in file

I'm building a custom task for grunt that finds a particular font, and basically outputs a definition that uses a PHP variable for configuring that particular font.
It uses underscore and postcss.
It groups all CSS selectors that use that font, and outputs a string similar to this one:
selector1, selector2, selector3 {
font-family: <?php echo $font_1 ?>, Font 2, Font 3, Font 4;
}
Here is the code for the custom task:
// Extract configurable font data
// ======================================================================
grunt.registerTask('extractfontdata', 'Extract configurable properties', function () {
console.log('Extracting configurable font data');
var match = /Myriad Pro/gim;
var contents = grunt.file.read('assets/css/leadscon.css');
var css = postcss(function (css) {
var findings = {};
css.eachDecl(function (decl) {
if (decl.value.match( match ) && decl.parent.selector !== undefined) {
var fonts = decl.value.replace(/(\r\n|\n|\r|"|')/gm, "").split(',');
var prop = _.find(fonts, function(font) { return font.match(match) });
var finding = findings[ prop ] = findings[ prop ] || {};
finding.selectors = finding.selectors || [];
finding.fontstack = finding.fontstack || [];
finding.selectors.push( decl.parent.selector.replace(/(\r\n|\n|\r|"|'|\s)/gm, "").split(',') );
finding.fontstack.push( fonts );
finding.selectors = _(finding.selectors).chain().flatten().uniq().value();
finding.fontstack = _(finding.fontstack).chain().flatten().uniq().value();
}
});
var result = '';
var j = 0;
for ( var font in findings ) {
findings[font].fontstack.every(function(f, i) {
if (f.match(font)) {
findings[font].fontstack[i] = '<?php echo $font_' + j++ + ' ?>';
}
});
result += findings[font].selectors.join(',') + ' { font-family: ' + findings[font].fontstack.join(',') + ' } ';
}
console.log(result);
// Now insert result into header.php
}).process(contents);
});
This currently, will set result to:
body,.footer-widget.widget_nav_menu.widget-title
{
font-family: <?php echo $font_0 ?>, PT Sans, Helvetica Neue, Helvetica, Arial, sans-serif
}
h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6,.widget.widget-title,.widget_lc_cta,.header-widget.widget_lc_events.events,.widget_accordion_widget.accordion-widget.resp-tabs-container>.resp-accordion,article.single>.article-header.breadcrumbs,article.single>.article-header.meta
{
font-family: <?php echo $font_1 ?>, Open Sans Condensed, PT Sans, Helvetica Neue, Helvetica, Arial, sans-serif
}
I've added this code to header.php:
<style>
/* extractfontdata */
</style>
Now, how do I find the string "extractfontdata" in header.php, and insert result after it?
Well in case anyone is wondering, this worked for me:
// Now insert result into header.php
var header = grunt.file.read('header.php').split('\n');
var line_1 = _.indexOf(header, _(header).find(function(el) { return el.match(/extractfontdata/i) }) );
var line_2 = _.indexOf(header, _(header).find(function(el) { return el.match(/endextractfontdata/i) }));
var start = Math.min(line_1, line_2) + 1;
var end = Math.max(line_1, line_2);
var num = Math.min((end - start), 0);
header.splice(start, num, result);
for ( var i = start-2; i <= end+2; i++) {
console.log(header[i]);
}
grunt.file.write('header.php', header.join('\n'));

PhoneGap 3.3.0 / Cordova iOS 7 Audio Record Permission

I am new to PhoneGap / Cordova development. Recently there was an update on iOS, and it requires users to grant permission to applications before they can use the microphone.
I had tried to update the "package" - Media and Media Capture, but it still not working.
I've also tried a plugin called cordova-phonegap-audio-encode, but it isn't working too.
The following are my code:
Record.html (This is a page / interface for users to interact and trigger the permission/recording audio)
<html>
<head>
<title>System</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="../js/cordova-2.3.0.js"></script>
<script src="../js/config.js"></script>
<script src="../js/languages.js"></script>
<script src="beJS.js"></script>
<link rel="stylesheet" href="../js/jquery.mobile-1.3.0.min.css" />
<script src="../js/jquery-1.8.2.min.js"></script>
<script src="../js/jquery.mobile-1.3.0.min.js"></script>
<script scr="../js/RecordPermission.js"></script>
</head>
<body >
<div data-role="page" id="beRecordPage">
<div data-role="header" data-theme="c" data-position="fixed">
<a href="index.html" id="btnMenu" target="_self" data-icon="home" data-ajax='false'></a>
<h1 id="be_header_record"></h1>
</div><!-- /header -->
<div data-role="content" >
<div class="content-primary" id='programContent' >
<label for="length" id="be_reocrd_lbl_scriptName"></label>
<input type="text" name='scriptName' id="scriptName" value="" data-clear-btn="true" maxlength="30"/>
<hr/>
<div data-role="controlgroup" >
<button type="button" data-theme="c" id="be_reocrd_btn_record" onclick='record();'></button>
<button type="button" data-theme="c" id="be_reocrd_btn_play" onclick='playRecord();'></button>
<button type="button" data-theme="c" id="be_reocrd_btn_delete" onclick='deleteRecord();'></button>
</div>
<div><!-- /content-primary -->
<div><!-- /content -->
</div><!-- /page -->
<script>
var isRecorded = false;
var isRecording = false;
var isPlaying = false;
var recordResult =false;
var lastSrc = "";
var src = "";
var mediaRec;
function playRecord(){
if(isRecorded && !isRecording){
if(isPlaying){
stopPlaying();
}else{
mediaRec = new Media(lastSrc, stopPlaying,null);
mediaRec.play();
isPlaying = true;
$('#be_reocrd_btn_record').button('disable');
$('#be_reocrd_btn_delete').button('disable');
$('#be_reocrd_btn_play').text(language[langCode].be_reocrd_btn_stop);
$('#be_reocrd_btn_play').button('refresh');
}
}else{
alert(language[langCode].be_reocrd_msg_pleaseRecord);
}
}
function deleteRecord(){
if(isRecorded && !isRecording && !isPlaying){
var confirmation=confirm(language[langCode].be_reocrd_msg_deleteConfirmation);
if(confirmation){
performDeleteRecord()
}
}else{
alert(language[langCode].be_reocrd_msg_deleteError);
}
}
var fileRoot;
function onFileSystemSuccess(fileSystem) {
fileRoot = fileSystem.root;
fileRoot.getFile(lastSrc, {create: false}, onGetFileSuccess, onError);
}
function onGetFileSuccess(entry){
entry.remove(function() {
var idx = --localStorage.SYS_RECORDFILEINDEX;
localStorage.removeItem("SYS_RECORD_NAME"+idx);
localStorage.removeItem("SYS_RECORD_PATH"+idx);
alert(language[langCode].be_reocrd_msg_deleteSuccessful);
}, onError
);
}
function onError() {
alert(language[langCode].be_reocrd_msg_deleteFailure);
}
function onRequestFileSystemSuccess(fileSystem) {
src = fileSystem.root.fullPath + '/' + src;
fileSystem.root.getFile(src, {create: true}, function() {
mediaRec = new Media(src, successRecord,failRecord);
mediaRec.startRecord();
}, function(err) {
alert(err.message);
}
);
/*
var entry=fileSystem.root;
entry.getDirectory(recordFileFolder, {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail);
*/
}
function onGetDirectorySuccess(dir) {
alert("Created dir "+dir.name);
mediaRec = new Media(src, successRecord,failRecord);
mediaRec.startRecord();
}
function onGetDirectoryFail(error) {
alert("Error creating directory "+error.code);
}
function performDeleteRecord(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
return true;
}
function successRecord(){
isRecorded = true;
recordResult = true;
lastSrc = src;
var idx = localStorage.SYS_RECORDFILEINDEX;
localStorage["SYS_RECORD_NAME"+idx] = $('#scriptName').attr('value');
localStorage["SYS_RECORD_PATH"+idx] = lastSrc;
localStorage.SYS_RECORDFILEINDEX++;
}
function stopPlaying(){
if(mediaRec != null){
mediaRec.stop();
mediaRec = null;
}
isPlaying = false;
$('#be_reocrd_btn_record').button('enable');
$('#be_reocrd_btn_delete').button('enable');
$('#be_reocrd_btn_play').text(language[langCode].be_reocrd_btn_play);
$('#be_reocrd_btn_play').button('refresh');
}
function failRecord(err){
alert(err.message);
alert(language[langCode].be_reocrd_msg_recordFailure);
$('#be_reocrd_btn_record').text(language[langCode].be_reocrd_btn_start);
recordResult = false;
}
function performRecord(){
var result = false;
src = recordFileFolder+new Date().getTime()+".wav";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null);
// mediaRec = new Media(src, successRecord,failRecord);
// mediaRec.startRecord();
}
function record(){
if($('#scriptName').attr('value') == ''){
alert(language[langCode].be_reocrd_msg_pleaseInputName);
return;
}
if(!isPlaying){
if(!isRecording){
$('#be_reocrd_btn_record').text(language[langCode].be_reocrd_btn_stop);
$('#be_reocrd_btn_play').button('disable');
$('#be_reocrd_btn_delete').button('disable');
isRecording = true;
performRecord();
}else{
mediaRec.stopRecord();
isRecording = false;
$('#be_reocrd_btn_record').text(language[langCode].be_reocrd_btn_start);
$('#be_reocrd_btn_play').button('enable');
$('#be_reocrd_btn_delete').button('enable');
}
$('#be_reocrd_btn_record').button('refresh');
}else{
alert(language[langCode].be_reocrd_msg_pleaseStopPlaying);
}
}
$('#beRecordPage').live('pagecreate',function(event){
checkLoggedIn();
$('#be_header_record').text(language[langCode].be_header_record);
$('#btnMenu').text(language[langCode].menu);
$('#be_reocrd_lbl_scriptName').text(language[langCode].be_reocrd_lbl_scriptName);
$('#be_reocrd_btn_record').text(language[langCode].be_reocrd_btn_start);
$('#be_reocrd_btn_play').text(language[langCode].be_reocrd_btn_play);
$('#be_reocrd_btn_delete').text(language[langCode].be_reocrd_btn_delete);
});
</script>
</body>
</html>
This is the RecordPermission.js
window.recordPermission = function(params) {
cordova.exec(function(answer){
if (answer === "True") params.success(true);
else if (answer === "False") params.success(false);
else params.error('success called with "'+answer+'". Must be "True" or "False" strings');
}, params.error,"RecordPermission", "recordPermission");
};
The following is RecordPermission.m
#import "RecordPermission.h"
#implementation RecordPermission
#synthesize callbackId;
- (void)recordPermission:(CDVInvokedUrlCommand*)command
{
self.callbackId = command.callbackId;
// First check to see if we are in ios 7.
NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:#"."];
if ([[vComp objectAtIndex:0] intValue] < 7) {
// before iOS7 when this permission was not required or setable by the user
[self performSelectorOnMainThread:#selector(doSuccessCallback:) withObject:#"True" waitUntilDone:NO];
} else {
// run this in a try just in case
#try {
[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
// cast this to a string bc I don't know if you can or how to pass a boolean back to javascript.
// This is converted back to a javascript boolean in RecordPermission.h.js file
NSString * grantedString = (granted) ? #"True" : #"False";
// talking back to javascript must be done in main thread.
[self performSelectorOnMainThread:#selector(doSuccessCallback:) withObject:grantedString waitUntilDone:NO];
}];
} #catch (id exception) {
NSLog(#"recordPermission try error");
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_JSON_EXCEPTION messageAsString:[exception reason]];
NSString* javaScript = [pluginResult toErrorCallbackString:command.callbackId];
[self writeJavascript:javaScript];
}
}
}
-(void) doSuccessCallback:(NSString*)granted {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:granted];
NSString* javaScript = [pluginResult toSuccessCallbackString:self.callbackId];
[self writeJavascript:javaScript];
}
#end
This is the RecordPermission.h
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <Cordova/CDV.h>
#interface RecordPermission : CDVPlugin{
NSString* callbackId;
}
#property (nonatomic, retain) NSString* callbackId;
- (void)recordPermission:(NSArray*)arguments ;
#end
So far I cannot trigger the permission and I checked "Settings" where the app does not appear at the "Microphone" page.
Please help! Thank you.

Opening tabs in Chrome news reader extension

I'm trying to create a simple chrome extension using the following google RSS reader sample,
http://code.google.com/chrome/extensions/samples.html#597015d3bcce3da693b02314afd607bec4f55291
I can add links in the pop-up window that open tabs, but not from the feeds themselves.
Looping through the items in the feed, grabbing title tags and link tags, I want the title to link the the appropriate sites
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for this feed item
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var title = document.createElement("a");
title.className = "item_title";
title.innerText = itemTitle; //display title in iframe
title.addEventListener("click", titleLink); // should open link when clicking on title, but does not.
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(itemLink);
}
Any thoughts on why this is not working.
If I replace title.addEventListener("click", titleLink); with title.addEventListener("click", moreStories); each title will link to moreStories, I cannot get each title to link to itemLink.
Thanks
Its a bit hard to answer your question without the whole code, but Ill give it a shot ;)
First up, titleLink() isnt going to work because itemLink isnt known. When you create title (the link) you should of attached it to that...say title.href=itemLink then in tiltleLinks you could access that href with showUrl(event.currentTarget.href)
Also did you fix the error in that example?...if not then change frameLoaded to....
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var clssName = links[i].className;
if (clssName != "item_title" && clssName != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
If you still have probs could you attach the whole code so I can see what your doing and Ill give you a hand.
Thank you very much for your help.
code title.href=itemLink and code showUrl(event.currentTarget.href) was exactly what I needed.
For completeness, here is the full code,
<script id="iframe_script">
function reportHeight() {
var msg = JSON.stringify({type:"size", size:document.body.offsetHeight});
parent.postMessage(msg, "*");
}
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var class = links[i].className;
if (class != "item_title" && class != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
function showStory(event) {
var href = event.currentTarget.href;
parent.postMessage(JSON.stringify({type:"show", url:href}), "*");
event.preventDefault();
}
function messageHandler(event) {
reportHeight();
}
</script>
<script>
// Feed URL.
var feedUrl = 'http://localhost/newsfeed.xml';
// The XMLHttpRequest object that tries to load and parse the feed.
var req;
function main() {
req = new XMLHttpRequest();
req.onload = handleResponse;
req.onerror = handleError;
req.open("GET", feedUrl, true);
req.send(null);
}
// Handles feed parsing errors.
function handleFeedParsingFailed(error) {
var feed = document.getElementById("feed");
feed.className = "error";
feed.innerText = "Error: " + error;
}
// Handles errors during the XMLHttpRequest.
function handleError() {
handleFeedParsingFailed('Failed to fetch RSS feed.');
}
// Handles parsing the feed data we got back from XMLHttpRequest.
function handleResponse() {
var doc = req.responseXML;
if (!doc) {
handleFeedParsingFailed("Not a valid feed.");
return;
}
buildPreview(doc);
}
// The maximum number of feed items to show in the preview.
var maxFeedItems = 10;
// Where the more stories link should navigate to.
var moreStoriesUrl;
function buildPreview(doc) {
// Get the link to the feed source.
var link = doc.getElementsByTagName("link");
var parentTag = link[0].parentNode.tagName;
if (parentTag != "item" && parentTag != "entry") {
moreStoriesUrl = link[0].textContent;
}
// Setup the title image.
var images = doc.getElementsByTagName("image");
var titleImg;
if (images.length != 0) {
var urls = images[0].getElementsByTagName("url");
if (urls.length != 0) {
titleImg = urls[0].textContent;
}
}
var img = document.getElementById("title");
// Listen for mouse and key events
if (titleImg) {
img.src = titleImg;
if (moreStoriesUrl) {
document.getElementById("title_a").addEventListener("click",moreStories);
document.getElementById("title_a").addEventListener("keydown",
function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
}
} else {
img.style.display = "none";
}
// Construct the iframe's HTML.
var iframe_src = "<!doctype html><html><head><script>" +
document.getElementById("iframe_script").textContent + "<" +
"/script></head><body onload='frameLoaded();' " +
"style='padding:0px;margin:0px;'>";
var feed = document.getElementById("feed");
// Set ARIA role indicating the feed element has a tree structure
feed.setAttribute("role", "tree");
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for the feed item.
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var item = document.createElement("div");
var title = document.createElement("a");
title.innerText = itemTitle; //display title in iframe
title.href=itemLink;
title.addEventListener("click", titleLink);
item.appendChild(title);
feed.appendChild(item);
}
if (moreStoriesUrl) {
var more = document.createElement("a");
more.className = "more";
more.innerText = "***Site Main Page*** \u00BB";
more.tabIndex = 0;
more.addEventListener("click", moreStories);
more.addEventListener("keydown", function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
feed.appendChild(more);
}
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
// -------------------------------------------------------------------
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(event.currentTarget.href);
}
function keyHandlerShowDesc(event) {
// Display content under heading when spacebar or right-arrow pressed
// Hide content when spacebar pressed again or left-arrow pressed
// Move to next heading when down-arrow pressed
// Move to previous heading when up-arrow pressed
if (event.keyCode == 32) {
showDesc(event);
} else if ((this.parentNode.className == "item opened") &&
(event.keyCode == 37)) {
showDesc(event);
} else if ((this.parentNode.className == "item") && (event.keyCode == 39)) {
showDesc(event);
} else if (event.keyCode == 40) {
if (this.parentNode.nextSibling) {
this.parentNode.nextSibling.children[1].focus();
}
} else if (event.keyCode == 38) {
if (this.parentNode.previousSibling) {
this.parentNode.previousSibling.children[1].focus();
}
}
}
function showDesc(event) {
var item = event.currentTarget.parentNode;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var iframe = items[i].getElementsByClassName("item_desc")[0];
if (items[i] == item && items[i].className == "item") {
items[i].className = "item opened";
iframe.contentWindow.postMessage("reportHeight", "*");
// Set the ARIA state indicating the tree item is currently expanded.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "true");
iframe.tabIndex = 0;
} else {
items[i].className = "item";
iframe.style.height = "0px";
// Set the ARIA state indicating the tree item is currently collapsed.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "false");
iframe.tabIndex = -1;
}
}
}
function iframeMessageHandler(e) {
// Only listen to messages from one of our own iframes.
var iframes = document.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].contentWindow == e.source) {
var msg = JSON.parse(e.data);
if (msg) {
if (msg.type == "size") {
iframes[i].style.height = msg.size + "px";
}
else if (msg.type == "show") {
var url = msg.url;
if (url.indexOf("http://localhost/index.html") == 0) {
// If the URL is a redirect URL, strip of the destination and go to
// that directly. This is necessary because the Google news
// redirector blocks use of the redirects in this case.
var index = url.indexOf("&url=");
if (index >= 0) {
url = url.substring(index + 5);
index = url.indexOf("&");
if (index >= 0)
url = url.substring(0, index);
}
}
showUrl(url);
}
}
return;
}
}
}
window.addEventListener("message", iframeMessageHandler);
</script>
Thanks again for the help.
-Mike

Resources