Архив

Архив раздела ‘Javascript’
5 августа 2021 Нет комментариев

В примере по клику на i в блоке .link скопировать ссылку внутри этого блока

function copyToClipboard(textToCopy){
	if(navigator.clipboard&&window.isSecureContext){
		return navigator.clipboard.writeText(textToCopy);
	}
	else{
		let textArea=document.createElement("textarea");
		textArea.value=textToCopy;
		textArea.style.position="fixed";
		textArea.style.left="-999999px";
		textArea.style.top="-999999px";
		document.body.appendChild(textArea);
		textArea.focus();
		textArea.select();
		return new Promise((res,rej)=>{
			document.execCommand('copy')?res():rej();
			textArea.remove();
		});
	}
}
$(document).ready(function(){
	$('.link i').on('click',function(){
		var link=$(this).closest('.link').find('a').attr('href');
		copyToClipboard(link).then(()=>console.log('copied')).catch(()=>console.log('not copied'));
	});
});
Categories: Javascript Tags:

javascript:

function canUseWebp(){
	let elem=document.createElement('canvas');
	if(!!(elem.getContext&&elem.getContext('2d'))){
		return elem.toDataURL('image/webp').indexOf('data:image/webp')==0;
	}
	return false;
}
window.onload=function(){
	let images=document.querySelectorAll('[data-bg]');
	for(let i=0;i<images.length;i++){
		let image=images[i].getAttribute('data-bg');
		images[i].style.backgroundImage='url('+image+')';
	}
	let isitFirefox=window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
	let firefoxVer=isitFirefox?parseInt(isitFirefox[1]):0;
	if(canUseWebp()||firefoxVer>=65){
		let imagesWebp=document.querySelectorAll('[data-bg-webp]');
		for(let i=0;i<imagesWebp.length;i++){
			let imageWebp=imagesWebp[i].getAttribute('data-bg-webp');
			imagesWebp[i].style.backgroundImage='url('+imageWebp+')';
		}
	}
};

html:

<div class="item" style="background-image:url('/img/banners/banner2.webp');" data-bg="/img/banners/banner2.jpg" data-bg-webp="/img/banners/banner2.webp"></div>

пример программного вывода:

function attr_background_image($image,$dir,$add=''){
	$html='';
	$image_path=ROOT_HTTP.$dir.$image;
	$image_pathinfo=pathinfo($image_path);
	$ext=($image_pathinfo['extension']=='jpg')?'jpeg':$image_pathinfo['extension'];
	if(USE_WEBP==1&&$ext!='svg'&&file_exists(ROOT_DIR.$dir.$image_pathinfo['filename'].'.webp')){
		$html.=' style="background-image:url(\''.ROOT_HTTP.$dir.$image_pathinfo['filename'].'.webp\');" data-bg="'.ROOT_HTTP.$dir.$image.'" data-bg-webp="'.ROOT_HTTP.$dir.$image_pathinfo['filename'].'.webp"';
	}
	else{
		$html.=' style="background-image:url(\''.ROOT_HTTP.$dir.$image.'\');'.$add.'"';
	}
	return $html;
}
$block_bg='';
if($block['photo']||$block['bgcolor']){
	if($block['photo']){
		$bgcolor='';
		if($block['bgcolor']){
			$bgcolor.='background-color:'.$block['bgcolor'].';';
		}
		$block_bg=attr_background_image($block["photo"],IMAGES_BLOCKS_DIR,$bgcolor);
	}
	elseif($block['bgcolor']){
		$block_bg.=' style="';
		$block_bg.='background-color:'.$block['bgcolor'].';';
		$block_bg.='"';
	}
}

или

<div class="item"<?=attr_background_image($item["photo"],IMAGES_BANNERS_DIR)?>>

https://webinmind.ru/javascript/webp-to-background-image

Categories: Javascript, PHP Tags: , ,
var char_timeout=50;
var story_timeout=2000;
var placeholders=new Array();
	placeholders[0]='труба';
	placeholders[1]='проточный водонагреватель';
	placeholders[2]='фильтр';
	placeholders[3]='бак';
	placeholders[4]='сифон';
	placeholders[5]='теплый пол';
	placeholders[6]='душевая кабина';
	placeholders[7]='емкость';
	placeholders[8]='горелка';
	placeholders[9]='арматура';
	placeholders[10]='бойлер';
	placeholders[11]='газовый котел';
	placeholders[12]='наcос';
function start_printing(){
	item_count=Number(placeholders.length);
	current_placeholder=-1;
	current_length=0;
	input=$('input[name=search_string]');
	run_printing();
}
function run_printing(){
	var timeout;
	if(current_length==0){
		current_placeholder++;
		current_placeholder=current_placeholder%item_count;
		placeholder=placeholders[current_placeholder].replace(/"/g,'-');
	}
	input.attr('placeholder',placeholder.substring(0,current_length)+current_char());
	if(current_length!=placeholder.length){
		current_length++;
		timeout=char_timeout;
	}
	else{
		current_length=0;
		timeout=story_timeout;
	}
	setTimeout("run_printing()",timeout);
}
function current_char(){
	if(current_length==placeholder.length){
		return "";
	}
	else{
		return "|";
	}
}
start_printing();
Categories: Javascript Tags:
$('input[type=number]').keyup(function(){
	var max=parseInt($(this).attr('max'));
	var min=parseInt($(this).attr('min'));
	var val=$(this).val();
	if(val<min){
		$(this).val(min);
	}
	if(val>max){
		$(this).val(max);
	}
});
Categories: Javascript Tags:
try{
	var result=JSON.parse(r);
	//...
}
catch(e){
}
Categories: Javascript Tags:
$(".element").prop("clientWidth");
//или
$(".element").prop("scrollWidth");

вместо

$('.element').width()
Categories: Javascript Tags:
(function($){
	$.widget("ui.onDelayedKeyup",{
		_init:function(){
			var self=this;
			$(this.element).keyup(function(){
				if(typeof(window['inputTimeout'])!="undefined"){
					window.clearTimeout(inputTimeout);
				}
				var handler=self.options.handler;
				window['inputTimeout']=window.setTimeout(function(){
					handler.call(self.element)
				},self.options.delay);
			});
		},
		options:{
			handler:$.noop(),
			delay:500
		}
	});
})(jQuery);
$('header .search input[type=text]').onDelayedKeyup({
	handler:function(){
		var string=$(this).val();
		if(string.length>3){
			//.......
		}
	},
	delay:1000
});
Categories: Javascript Tags: