если неправильно указан DOM-элемент, как это узнать
$('#content').on('click' ,'#singleclick', function () {
debugger;
var product = $(this).parents('.product-block');
$('#product_name').val(product.find('.product-action .name a').text());
$('#product_price').val(product.find('.product-action .price').text());
$('#singleclick_title').text(product.find('.product-action .name a').text());
});
var links = $('.ofice a[title]').map(function(){
return $(this).attr('title');
});
var links = Array.prototype.map.call(document.querySelectorAll('.ofice a[title]'),function(el){
return el.getAttribute('title');
});
/**
*
* @param duration - продолжительность работы таймера
* @param interval - время тика таймера
* @param from - начальное значение
* @param to - конечное значение
* @param minStep - минимальный шаг вызова callback
* @param callback - обработчик
*/
function timer(duration,interval,from,to,minStep,callback){
var value=from,
forward=(from<to),
range=Math.abs(to-from),
steps=duration/interval,
step=range/steps,
last=from,
handle=setInterval(function(){
value+=step*(forward?1:-1);
if(forward?value>to:value<to){
value=to;
clearInterval(handle);
handle=null;
}
if(!minStep||!handle||Math.abs(last-value)>=minStep){
last=value;
callback(value,from,to);
}
}
,interval);
return handle;
}
timer(800,20,50,0,1,function(value){
console.warn(Math.floor(value));
})
Функционал чата таков: текстовое и видео общение. Проблема, собственно в том, что я не знаю JavaScript, а найти и впаять хороший чат не получается.
Пользователей будет около 5-10 миллионов
var test=function(){
this.enable = false;
this.protectedFunc1=function(){
console.warn('Protected func1 called!');
}
this.protectMethod=function(fn){
var self=this,
fn;
if(typeof fn!=='function'){
throw TypeError('Given thing is not a function!');
}
return function(){
console.log(self.enable);
if(!self.enable){
throw Error('Access to protected method not allowed');
}
return fn.apply(self,arguments);
};
}
this.protectedFunc1=this.protectMethod(this.protectedFunc1);
this.protectedFunc2=this.protectMethod(function(args){
console.warn('Protected func1 called!');
})
}
var obj=new test;
obj.enable=true;
obj.protectedFunc1(); //Protected func1 called!
obj.enable=false;
obj.protectedFunc1();// Error: Access to protected method not allowed
var beers=[1,{locale:'domestic'},5,6,{locale:'domestic'},0,{locale:'domestic'}];
beers.reduceBeers = function () {
var stack=[];
this.forEach(function(item,index){
if (item.locale === 'domestic') {
stack.push(item);
}
});
this.length = 0;//empty an Array;
this.push.apply(this,stack);
return this;
};
beers.reduceBeers();
beers.reduceBeers = function () {
var stack=this.filter(function(item,index){
return item.locale === 'domestic';
})
this.length = 0;//empty an Array;
this.push.apply(this,stack);
return this;
};
function myFunc(){
var el=document.getElementById('tt2'),
str=el.style.transform,
translate=(/translate\((\S+?),\s(\S+?)\)/i.exec(str)||[0,0]),
translateX=parseInt(translate[1]); //-66.6%
translateX+=33.3;
console.log(translateX);
el.style.transform = "translate(" +translateX+"%,0)";
}
<div id="tt2" class="slider">
<div><div>Digital</div><div>Brain</div><div>created</div><div>this</div></div>
</div>
<button onclick="slider.prev();">Prev</button>
<button onclick="slider.next();">Next</button>
.slider{
width:30%;
height:100px;
background-color: green;
overflow: hidden;
position: relative;
}
.slider>div{
display: inline-block;
height:100%;
white-space: nowrap;
position: relative;
width:100%;
padding: 0;
-webkit-transition: all 1s cubic-bezier(0.5, 0, 0.5, 1);
}
.slider>div>div{
display: inline-block;
width:100%;
height:100%;
text-align:center;
margin: 0;
}
function Slider(el){
var $el=(typeof el=="string")?document.getElementById(el):el,
content=$el.getElementsByTagName('div')[0],
sliders=content.getElementsByTagName('div'),
count=sliders.length,
width=content.offsetWidth,
step=width/count;
this.index=0;
function setTX(value){
content.style.transform = "translate(" +value+"%,0)";
}
this.showIndex=function(index){
console.info(index);
var max=count-1;
if(index>max){
index=0;
}else if(index<0){
index=max;
}
console.log('index=',index,max);
this.index=index;
setTX(index*(-100));
}
this.next=function(){
console.log('next');
this.showIndex(++this.index)
}
this.prev=function(){
console.log('prev');
this.showIndex(--this.index)
}
}
var slider=new Slider("tt2");
if( window.location.hash != pages) window.location.hash = pages;
xmlhttp.onreadystatechange=function(){}
xmlhttp.send("id="+id+"&hash="+hash);
{"success":"true","data":{}}//ok
{"success:"false","error":{"code":1,"message":"bla"}//error
//success- избыточен, но есть на него идейные любители
function replaceWord(str,index,tag){
return str.substr(0,index)+str.substr(index).replace(/\w+/,"<"+tag+">$&</"+tag+">");
}
console.log(replaceWord("Hello World!",6,"strong"));
function replaceWord(str,index,tag){
return str.substr(0,index)+str.substr(index).replace(/[_0-9a-zA-Zа-яёА-ЯЁ]+/,"<"+tag+">$&</"+tag+">");
}
console.log(replaceWord("Привет Мир!!",7,"strong"));
console.log(replaceWord("Функция — это самый мощный инструмент для замены, какой только может быть.",14,"strong"));
//Привет <strong>Мир</strong>!!
//Функция — это <strong>самый</strong> мощный инструмент для замены, какой только может быть.
var likeArrayObject = {
0: "a",
1: "b",
2: "c",
3: "d",
4: "e",
length: 5
},
arr = Array.prototype.slice.call(likeArrayObject, 1, 4); //теперь это массив
console.log(likeArrayObject);
console.log(arr);
function getData(url, callback) {
var RESPONSES = {
'/countries': [
{name: 'Cameroon', continent: 'Africa'},
{name :'Fiji Islands', continent: 'Oceania'},
{name: 'Guatemala', continent: 'North America'},
{name: 'Japan', continent: 'Asia'},
{name: 'Yugoslavia', continent: 'Europe'},
{name: 'Tanzania', continent: 'Africa'}
],
'/cities': [
{name: 'Bamenda', country: 'Cameroon'},
{name: 'Suva', country: 'Fiji Islands'},
{name: 'Quetzaltenango', country: 'Guatemala'},
{name: 'Osaka', country: 'Japan'},
{name: 'Subotica', country: 'Yugoslavia'},
{name: 'Zanzibar', country: 'Tanzania'},
],
'/populations': [
{count: 138000, name: 'Bamenda'},
{count: 77366, name: 'Suva'},
{count: 90801, name: 'Quetzaltenango'},
{count: 2595674, name: 'Osaka'},
{count: 100386, name: 'Subotica'},
{count: 157634, name: 'Zanzibar'}
]
};
setTimeout(function () {
var result = RESPONSES[url];
if (!result) {
return callback('Unknown url');
}
callback(null, result);
}, Math.round(Math.random * 1000));
}
/**
* Ваши изменения ниже
*/
var requests = ['/countries', '/cities', '/populations'];
var responses = {}; //, counter=0;
for (var i = 0; i < 3; i++) {
var _request = requests[i];
var callback = function(request){
return function (error, result) {
responses[request] = result;
var i, j;
if (Object.keys(responses).length == 3) { //or counter++==3
var c = [], cc = [], p = 0;
for (i = 0; i < responses['/countries'].length; i++) {
if (responses['/countries'][i].continent === 'Africa') {
c.push(responses['/countries'][i].name);
}
}
for (i = 0; i < responses['/cities'].length; i++) {
for (j = 0; j < c.length; j++) {
if (responses['/cities'][i].country === c[j]) {
cc.push(responses['/cities'][i].name);
}
}
}
for (i = 0; i < responses['/populations'].length; i++) {
for (j = 0; j < cc.length; j++) {
if (responses['/populations'][i].name === cc[j]) {
p += responses['/populations'][i].count;
}
}
}
console.log('Total population in African cities: ' + p);
}
}
}(_request);
getData(_request, callback);
}
var requests = ['/countries', '/cities', '/populations'];
var responses = {};
function load(request){
return new Promise(function(resolve,reject){
getData(request,function(error, result){
if(!error){
resolve(result);
}else{
reject (error);
}
})
});
}
function getPopulation(state){
return Promise.all(requests.map(function(request){
return load(request);
})).then(function(data){
//console.log(arguments);
var countries=data[0],
cities=data[1],
populations=data[2],
result;
console.log(countries,cities,populations);
//calc here for state
return result;
},function(error){
console.warn("Data error",error);
});
}
getPopulation("Africa").then(console.log);