Ok, can you spot a syntax error here? - javascript

Eclipse is givign me a syntax error along these lines but I don't see anything wrong there:
$('.addNewFolder').click(function() {
showModal('modal_div', 'Nový adresár');
var id = '<?php echo ToHtml($idFolder); ?>';
$('.folders .trow1').each(function() {
if ($(this).css('backgroundColor') == 'rgb(52, 108, 182)' || $(this).css('backgroundColor') == '#346cb6') {
id = $(this).attr('rel');
}
});
ajaxElementCall('modal_div', 'body/obsah/obrazy/folderAdd.php?idFolder='+id);
});
After PHP parsing:
$('.addNewFolder').click(function() {
showModal('modal_div', 'Nový adresár');
var id = '';
$('.folders .trow1').each(function() {
if ($(this).css('backgroundColor') == 'rgb(52, 108, 182)' || $(this).css('backgroundColor') == '#346cb6') {
id = $(this).attr('rel');
}
});
ajaxElementCall('modal_div', 'body/obsah/obrazy/folderAdd.php?idFolder='+id);
});
This is what IDE says:
Syntax error on token "}", invalid MethodHeaderName
I've been staring at that code for at least half an hour. I am either blind or going crazy.
EDIT:
The whole javascript on the page:
<script type="text/javascript">
//<!--
$(document).ready(function() {
function in_array (needle, haystack, argStrict) {
var key = '', strict = !!argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true; }
}
} else {
for (key in haystack) {
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
var openedFolders = new Array();
<?php if (count($_SESSION['ECM']['openedSlideFolders']) > 0) : ?>
<?php $i = 0; foreach ($_SESSION['ECM']['openedSlideFolders'] as $aVal): ?>
<?php echo "openedFolders[$i] = '$aVal';\n"; ?>
<?php ++$i; endforeach; ?>
<?php endif; ?>
var start = 0;
var stop = 0;
$('.drag').each(function() {
var draggables = $(this).parents('table').find('.drag');
var $next = draggables.filter(':gt(' + draggables.index(this) + ')').first();
var width = $(this).css('width');
var nextWidth = $next.css('width');
if (nextWidth > width && 30 == parseInt(width)) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
if (in_array($(this).attr('rel'), openedFolders)) {
$(this).addClass('ordinaryFolderOpened');
} else {
$(this).addClass('ordinaryFolderClosed');
}
}
if (in_array($(this).attr('rel'), openedFolders)) {
start = 1;
}
if (1 == start && stop < 2) {
if (30 == parseInt(width)) {
stop++;
}
} else {
start = 0;
stop = 0;
if (parseInt(width) > 30) {
$(this).parent().parent().hide();
}
}
});
function dragDrop()
{
$('.folders .trow1').hover(
function () {
if ($(this).css('backgroundColor') != 'rgb(52, 108, 182)' && $(this).css('backgroundColor') != '#346cb6') {
$(this).css('background', "#C2E3EF");
}
},
function () {
if ($(this).css('backgroundColor') != 'rgb(52, 108, 182)' && $(this).css('backgroundColor') != '#346cb6') {
$(this).css('background', 'transparent');
}
}
);
$('.drag').click(function() {
var draggables = $(this).parents('table').find('.drag');
var $next = draggables.filter(':gt(' + draggables.index(this) + ')').first();
var width = $(this).css('width');
var nextWidth = $next.css('width');
if (nextWidth > width && 30 == parseInt(width)) {
var isVisible = $next.is(':visible');
if (isVisible) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderClosed');
} else {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderOpened');
}
clickedId = $(this).attr('rel');
$.ajax({
type: 'POST',
url: 'body/obsah/obrazy/setOpenedFolder.php',
data: 'id='+clickedId,
success: function(msg){
//alert(msg);
}
});
var start = 0;
var stop = 0;
var i = 0;
$('.drag').each(function() {
if (0 == start) {
iteratedId = $(this).attr('rel');
if (iteratedId == clickedId) {
start = 1;
}
}
if (1 == start && stop < 2) {
if ($(this).css('width') > width) {
if (isVisible) {
$(this).parent().parent().hide();
} else {
$(this).parent().parent().show();
}
} else {
stop++;
}
}
i++;
});
}
});
var dragId = 0;
var dropId = 0;
var isFile = false;
$('.drag').mousedown(function() {
if ($(this).attr('rel') !== undefined) {
dragId = $(this).attr('rel');
dragId = dragId.split(',');
dragId = dragId[0];
}
isFile = false;
});
$('.drag2').mousedown(function() {
if ($(this).attr('rel') !== undefined) {
dragId = $(this).attr('rel');
dragId = dragId.split(',');
dragId = dragId[0];
}
isFile = true;
});
$('.drag').draggable({
revert: true,
cursorAt: {top: 0, left: 0}
});
$('.drag2').draggable({
revert: true,
cursorAt: {top: 0, left: 0}
});
$('.drop').droppable({
tolerance: 'pointer',
drop: function() {
if ($(this).attr('rel') !== undefined) {
dropId = $(this).attr('rel');
dropId = dropId.split(',');
dropId = dropId[0];
if (dropId != dragId) {
if (false == isFile) {
$.ajax({
type: 'POST',
url: 'body/obsah/obrazy/folderMove.php',
data: 'nid='+dragId+'&pid='+dropId,
success: function(msg){
<?php echo $aJsOnDrop; ?>;
dragDrop();
}
});
} else if (true == isFile) {
$.ajax({
type: 'POST',
url: 'body/obsah/obrazy/slideMove.php',
data: 'fid='+dragId+'&did='+dropId,
success: function(msg){
<?php echo $aJsOnDrop; ?>;
dragDrop();
}
});
}
}
}
}
});
}
dragDrop();
$('.folderListOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel')+'&browse=<?php echo $browse; ?>';
ajaxElementCall('obrazy_list', '<?php echo $dirPrefixBody; ?>/listBase.php?'+append);
dragDrop();
$('.trow1').css('background', 'transparent');
$('.trow1').css('color', '#3e4245');
$(this).parent().css('background', "#346cb6 url('img/menuButtonOver.png') left top repeat-x");
$(this).parent().css('color', 'white');
});
$('.rootFolderListOnclick').click(function() {
window.location = 'navigator.php?kam=obrazy';
dragDrop();
});
$('.folderEditOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel');
showModal('modal_div', 'Editácia adresára');
ajaxElementCall('modal_div', '<?php echo $dirPrefixBody; ?>/folderEdit.php?kam=edit1&'+append);
});
$('.folderDeleteOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel');
showModal('modal_div', 'Vymazanie adresára');
// TODO 0 Nemam sajnu, aka chyba je tuna - Eclipse mi tu hadze syntax error
ajaxElementCall('modal_div', '<?php echo $dirPrefixBody; ?>/folderDelete.php?kam=del1&'+append);
});
$('.addNewFolder').click(function() {
showModal('modal_div', 'Nový adresár');
var id = '<?php echo ToHtml($idFolder); ?>';
$('.folders .trow1').each(function() {
if ($(this).css('backgroundColor') == 'rgb(52, 108, 182)' || $(this).css('backgroundColor') == '#346cb6') {
id = $(this).attr('rel');
}
});
ajaxElementCall('modal_div', 'body/obsah/obrazy/folderAdd.php?idFolder='+id);
});
}); //-->
</script>
After PHP parsing:
<script type="text/javascript">
//<!--
$(document).ready(function() {
function in_array (needle, haystack, argStrict) {
var key = '', strict = !!argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true; }
}
} else {
for (key in haystack) {
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
var openedFolders = new Array();
openedFolders[0] = '3';
var start = 0;
var stop = 0;
$('.drag').each(function() {
var draggables = $(this).parents('table').find('.drag');
var $next = draggables.filter(':gt(' + draggables.index(this) + ')').first();
var width = $(this).css('width');
var nextWidth = $next.css('width');
if (nextWidth > width && 30 == parseInt(width)) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
if (in_array($(this).attr('rel'), openedFolders)) {
$(this).addClass('ordinaryFolderOpened');
} else {
$(this).addClass('ordinaryFolderClosed');
}
}
if (in_array($(this).attr('rel'), openedFolders)) {
start = 1;
}
if (1 == start && stop < 2) {
if (30 == parseInt(width)) {
stop++;
}
} else {
start = 0;
stop = 0;
if (parseInt(width) > 30) {
$(this).parent().parent().hide();
}
}
});
function dragDrop()
{
$('.folders .trow1').hover(
function () {
if ($(this).css('backgroundColor') != 'rgb(52, 108, 182)' && $(this).css('backgroundColor') != '#346cb6') {
$(this).css('background', "#C2E3EF");
}
},
function () {
if ($(this).css('backgroundColor') != 'rgb(52, 108, 182)' && $(this).css('backgroundColor') != '#346cb6') {
$(this).css('background', 'transparent');
}
}
);
$('.drag').click(function() {
var draggables = $(this).parents('table').find('.drag');
var $next = draggables.filter(':gt(' + draggables.index(this) + ')').first();
var width = $(this).css('width');
var nextWidth = $next.css('width');
if (nextWidth > width && 30 == parseInt(width)) {
var isVisible = $next.is(':visible');
if (isVisible) {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderClosed');
} else {
$(this).removeClass('ordinaryFolderClosed');
$(this).removeClass('ordinaryFolderOpened');
$(this).addClass('ordinaryFolderOpened');
}
clickedId = $(this).attr('rel');
$.ajax({
type: 'POST',
url: 'body/obsah/obrazy/setOpenedFolder.php',
data: 'id='+clickedId,
success: function(msg){
//alert(msg);
}
});
var start = 0;
var stop = 0;
var i = 0;
$('.drag').each(function() {
if (0 == start) {
iteratedId = $(this).attr('rel');
if (iteratedId == clickedId) {
start = 1;
}
}
if (1 == start && stop < 2) {
if ($(this).css('width') > width) {
if (isVisible) {
$(this).parent().parent().hide();
} else {
$(this).parent().parent().show();
}
} else {
stop++;
}
}
i++;
});
}
});
var dragId = 0;
var dropId = 0;
var isFile = false;
$('.drag').mousedown(function() {
if ($(this).attr('rel') !== undefined) {
dragId = $(this).attr('rel');
dragId = dragId.split(',');
dragId = dragId[0];
}
isFile = false;
});
$('.drag2').mousedown(function() {
if ($(this).attr('rel') !== undefined) {
dragId = $(this).attr('rel');
dragId = dragId.split(',');
dragId = dragId[0];
}
isFile = true;
});
$('.drag').draggable({
revert: true,
cursorAt: {top: 0, left: 0}
});
$('.drag2').draggable({
revert: true,
cursorAt: {top: 0, left: 0}
});
$('.drop').droppable({
tolerance: 'pointer',
drop: function() {
if ($(this).attr('rel') !== undefined) {
dropId = $(this).attr('rel');
dropId = dropId.split(',');
dropId = dropId[0];
if (dropId != dragId) {
if (false == isFile) {
$.ajax({
type: 'POST',
url: 'body/obsah/obrazy/folderMove.php',
data: 'nid='+dragId+'&pid='+dropId,
success: function(msg){
ajaxElementCall('__folderList', 'body/obsah/obrazy/folders.php?browse=0&idFolder=', 'obrazy_list', 'body/obsah/obrazy/listBase.php?browse=0&idFolder=');
dragDrop();
}
});
} else if (true == isFile) {
$.ajax({
type: 'POST',
url: 'body/obsah/obrazy/slideMove.php',
data: 'fid='+dragId+'&did='+dropId,
success: function(msg){
ajaxElementCall('__folderList', 'body/obsah/obrazy/folders.php?browse=0&idFolder=', 'obrazy_list', 'body/obsah/obrazy/listBase.php?browse=0&idFolder=');
dragDrop();
}
});
}
}
}
}
});
}
dragDrop();
$('.folderListOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel')+'&browse=0';
ajaxElementCall('obrazy_list', 'body/obsah/obrazy/listBase.php?'+append);
dragDrop();
$('.trow1').css('background', 'transparent');
$('.trow1').css('color', '#3e4245');
$(this).parent().css('background', "#346cb6 url('img/menuButtonOver.png') left top repeat-x");
$(this).parent().css('color', 'white');
});
$('.rootFolderListOnclick').click(function() {
window.location = 'navigator.php?kam=obrazy';
dragDrop();
});
$('.folderEditOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel');
showModal('modal_div', 'Editácia adresára');
ajaxElementCall('modal_div', 'body/obsah/obrazy/folderEdit.php?kam=edit1&'+append);
});
$('.folderDeleteOnclick').click(function() {
var append = 'idFolder='+$(this).attr('rel');
showModal('modal_div', 'Vymazanie adresára');
// TODO 0 Nemam sajnu, aka chyba je tuna - Eclipse mi tu hadze syntax error
ajaxElementCall('modal_div', 'body/obsah/obrazy/folderDelete.php?kam=del1&'+append);
});
$('.addNewFolder').click(function() {
showModal('modal_div', 'Nový adresár');
var id = '';
$('.folders .trow1').each(function() {
if ($(this).css('backgroundColor') == 'rgb(52, 108, 182)' || $(this).css('backgroundColor') == '#346cb6') {
id = $(this).attr('rel');
}
});
ajaxElementCall('modal_div', 'body/obsah/obrazy/folderAdd.php?idFolder='+id);
});
}); //-->
</script>

Having looked at the whole code (and pasted it, minus the PHP content, into The Online Lint), I'd still say that there's no syntax error in the Javascript, and that if that if Eclipse is telling you that there is, then Eclipse is wrong. Sometimes tools aren't perfect.
Does the code run, in different browsers? Chances are relatively good that if it does, then there's not actually a syntax error there.
(Posted as answer as requested. Ta.)

Try removing the accented characters in your quotes, you can still output accents, but use the corresponding HTML code.
A list of accented characters' HTML codes are found here:
http://www.w3schools.com/tags/ref_entities.asp

Related

How to html5 video duration speed control bypass

I am not a web developer. The institution I work for has online training. in html5 video form. Video acceleration doesn't work. There is a time control. If speeding is detected, the video restarts. Is there any way I can bypass this? The total duration of the trainings is 650 min. It is really hard. I am posting the source code of the video page.
<div style="position:relative">
<input type="hidden" id="pinfo" data-calisankodu="46564064386" data-calisanadsoyad="FATİH KURT" data-egitimkodu="1ae2b8e4-971f-4025-a8e2-97cbc60989bd"
data-egitimadi="2022 Temel İş Sağlığı ve Güvenliği Eğitimi" data-dokumankodu="35c46809-cc58-4806-a5e8-e921d65b8557" data-dosyaadi="01 Genel Konular_202104042129579656.mp4" data-dokumantanimi="01 genel konular"
data-dokumanaciklama="Genel Konular" data-calisanegitimkodu="dad47501-bdd3-4275-a01e-631e77ecc242" data-calisanegitimicerikkodu="d3439fcb-ad6b-41dd-bd87-592ba6f47325"
data-ks="765" data-kontrolkaldigisure="0" data-ts="2768" data-td="27" data-uzanti="mp4" data-vapo="1"
data-vks="0" data-isyerikodu="AEFC7F5C-7FA2-4A9E-83A3-6FED40C4A829" />
<div id="kontrolSorular" class="hidden"></div>
<div id="video-filigram" style="margin-left: 0px;" class="grid-stack hidden"></div>
<video id="dersvideo" playsinline controls preload="auto">
<source src="/UploadedFiles/01 Genel Konular_202104042129579656.mp4" type="video/mp4" size="1080">
Tarayıcınız video oynatmayı desteklemiyor.
And
//Genel değişkenler
var player;
var icerik = {};
var aktifsoru = 0;
var kconfirms = [];
var kontrolsorular = [];
var currenttime = 0;
var kontrolsure = 0;
var completedbefore = false;
var videoarkaplandaoynat = false;
var seektry = false;
var autosavesecond = 120;
var savetries = [];
var savetryconfirmed = false;
var isios = false;
var loadeddata = false;
var ilerisarma = 0;
var zorunluegitim = 1;
var kontrolegitimicerik = "";
var etkilesimliegitimicerik = "";
var EtkilesimliEgitimIzlenecekDokumanKodu = "";
var cevaplanankontrolegitimicerik = [];
var cevaplananetkilesimliegitimicerik = [];
var kontrolegitimiceriksure = -1;
var etkilesimliegitimiceriksure = -1;
var gecensure = 0;
var EgitimTuru = "1";
var VideoIleriSarma = "0";
if (EgitimTuru == "0" || VideoIleriSarma == "1") {
console.log("Video ileri sarma aktif");
ilerisarma = 5;
zorunluegitim = 0;
}
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/g)) {
console.log("iOS device detected");
console.log("Everything is OK.");
isios = true;
}
//Doc Ready
$(document).ready(function () {
//Load lesson content
icerik = {
CalisanKodu: $("#pinfo").attr("data-calisankodu"),
CalisanAdSoyad: $("#pinfo").attr("data-calisanadsoyad"),
EgitimKodu: $("#pinfo").attr("data-egitimkodu"),
EgitimAdi: $("#pinfo").attr("data-egitimadi"),
DokumanKodu: $("#pinfo").attr("data-dokumankodu"),
DosyaAdi: $("#pinfo").attr("data-dosyaadi"),
DokumanTanimi: $("#pinfo").attr("data-dokumantanimi"),
DokumanAciklama: $("#pinfo").attr("data-dokumanaciklama"),
CalisanEgitimKodu: $("#pinfo").attr("data-calisanegitimkodu"),
CalisanEgitimIcerikKodu: $("#pinfo").attr("data-calisanegitimicerikkodu"),
ToplamSure: parseInt($("#pinfo").attr("data-ts")),
KaldigiSure: parseInt($("#pinfo").attr("data-ks")),
KontrolKaldigiSure: parseInt($("#pinfo").attr("data-kontrolkaldigisure")),
TamamlanmaDurum: parseInt($("#pinfo").attr("data-td")),
Tamamlandi: false,
KontrolSure: -1,
EgitimKontrolIcerikKodu: kontrolegitimicerik,
EtkilesimliEgitimIcerikKodu: etkilesimliegitimicerik,
EgitimTuru: EgitimTuru,
GecenSure: 0
};
//Get lesson state
if (icerik.TamamlanmaDurum >= 100) {
completedbefore = true;
icerik.Tamamlandi = true;
}
//Player Install
player = new Plyr('#dersvideo', {
controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'settings', 'fullscreen'],
settings: ['captions','quality' /*,'speed' */ ],
preload: "auto",
i18n: {
restart: 'Sıfırla',
rewind: 'Kalan {seektime}',
play: 'Başlat',
pause: 'Durdur',
fastForward: 'İleri {seektime}',
seek: 'Aralık',
seekLabel: '{currentTime} of {duration}',
played: 'Oynatılan',
buffered: 'Önbellek',
currentTime: 'Şimdi',
duration: 'Süre',
volume: 'Ses',
mute: 'Sustur',
unmute: 'Sesi Aç',
enableCaptions: 'Altyazı Aç',
disableCaptions: 'Altyazı Kapat',
download: 'İndir',
enterFullscreen: 'Tam Ekran',
exitFullscreen: 'Kapat',
frameTitle: 'Oynatılıyor: {title}',
captions: 'Altyazılar',
settings: 'Ayarlar',
menuBack: 'Geri',
speed: 'Hız',
normal: 'Normal',
quality: 'Kalite',
loop: 'Tekrar',
start: 'Başlangıç',
end: 'Son',
all: 'Tümü',
reset: 'Sıfırla',
disabled: 'Gizle',
enabled: 'Göster',
advertisement: 'Duyuru',
qualityBadge: {
1080: 'Yuksek',
360: 'Dusuk',
},
capture: 'Ekran Görüntüsü'
},
keyboard:{ focused: false, global: false },
seekTime: ilerisarma,
fullscreen: { fallback: false },
listeners: {
seek: function (e) {
seektry = true;
var newTime = _getTargetTime(player, e);
if (newTime > icerik.KaldigiSure && completedbefore == false && zorunluegitim == "1") {
e.preventDefault();
console.log('prevented');
return false;
}
}
}
});
var vh = $(window).innerHeight();
let vw = $(window).innerWidth();
$("#dersvideo").css("height", vh + "px");
$(window).resize(function () {
let vh = $(window).innerHeight();
let vw = $(window).innerWidth();
$("#dersvideo").css("height", vh + "px");
});
$(window).bind("resize", function () {
let vh = $(window).innerHeight();
let vw = $(window).innerWidth();
$("#dersvideo").css("height", vh + "px");
});
//Get backgroundplay config
if ($("#pinfo").attr("data-vapo") == "1") {
videoarkaplandaoynat = true;
}
//Get client control config
if (Number($("#pinfo").attr("data-vks")) > 0) {
kontrolsure = Number($("#pinfo").attr("data-vks"))*60;
} else {
kontrolsure = Number(icerik.KontrolSure);
}
player.on('play', event => {
start();
});
player.on('pause', event => {
stop();
});
if (isios) {
//On play
player.once('play', event => {
console.log("duration: " + parseInt(player.duration) + " - After First Play");
icerik.ToplamSure = parseInt(player.duration);
player.currentTime = (icerik.KontrolKaldigiSure == 0) ? icerik.KaldigiSure : icerik.KontrolKaldigiSure;
});
} else {
//ShowWelcome();
if (icerik.Tamamlandi == false) {
console.log("start lesson");
player.play();
} else {
player.currentTime = (icerik.KontrolKaldigiSure == 0) ? 0 : icerik.KontrolKaldigiSure;
player.play();
}
player.play();
//On player get video data
player.once('loadeddata', event => {
loadeddata = true;
ShowButtons();
});
setTimeout(function () {
}
//player.on('enterfullscreen', event => { console.log(event); });
//player.on('exitfullscreen', event => { console.log(event); });
//Player on time update
player.on('timeupdate', event => {
currenttime = parseInt(player.currentTime);
if (currenttime > icerik.KaldigiSure || icerik.Tamamlandi == true) {
icerik.KaldigiSure = currenttime;
}
//Kontrol süresi özelliği eklendiğinde açılacak.
if (kontrolsure > 0 && player.playing && currenttime > 0 && currenttime % kontrolsure == 0) {
var cfrm = kconfirms.filter(x => x == currenttime);
if (cfrm.length == 0) {
kconfirms.push(currenttime);
player.pause();
}
}
/
// Eğitim Kontrol İçeriği Tetikletme
if (currenttime == kontrolegitimiceriksure && player.playing == true && cevaplanankontrolegitimicerik.indexOf(kontrolegitimicerik) == -1){
$("#video-filigram").removeClass("hidden");
player.pause();
SaveState(false);
$(".jconfirm").remove();
}
// Etkileşimli Eğitim İçeriği Tetikletme
if (currenttime == etkilesimliegitimiceriksure && player.playing == true && cevaplananetkilesimliegitimicerik.indexOf(etkilesimliegitimicerik) == -1) {
player.pause();
SaveState(false);
$(".jconfirm").remove();
window.location.href = "/Calisan/EtkilesimliIcerikViewer/" + etkilesimliegitimicerik + window.location.search + "&etkilesimliegitimicerik=" + etkilesimliegitimicerik + "&kaldigisure=" + player.currentTime + "&isyerikodu=" + $("#pinfo").attr("data-isyerikodu");
}
});
player.on('seeking', event => {
if (zorunluegitim=="0" || icerik.KaldigiSure >= player.currentTime || // video başı mı ?
((parseInt(kontrolegitimiceriksure) != parseInt(player.currentTime) && kontrolegitimiceriksure != -1)) ||
((parseInt(etkilesimliegitimiceriksure) != parseInt(player.currentTime) && etkilesimliegitimiceriksure != -1)) //|| kontrol içeriği var mı ve süre eşit mi ?
//parseInt(player.currentTime) == parseInt(player.duration) // video sonuna gelindi mi ?
//seektry == true
) {
}
else {
SaveState(true);
}
});
//Pause event
player.on('pause', event => {
console.log("paused");
if (parseInt(player.currentTime) == parseInt(player.duration)) {
if (player.currentTime < player.duration && (kontrolegitimiceriksure == -1 || etkilesimliegitimiceriksure == -1) ) {
LessonEnd();
}
//Respect end event
} else if (seektry == true) {
console.log("seektry");
seektry = false;
} else if (!player.fullscreen.active && aktifsoru == 0 && savetryconfirmed == false) {
if (parseInt(kontrolegitimiceriksure) != parseInt(player.currentTime) || parseInt(etkilesimliegitimiceriksure) != parseInt(player.currentTime))
{
$.confirm({
theme: 'supervan',
closeIcon: false,
title: 'Video Duraklatıldı',
content: completedbefore == false ? 'Videoya kaldığınız yerden devam edebilir ya da eğitimi sonlandırabilirsiniz.<br/><br/> <small><i class="fa fa-warning"></i> UYARI <br/> Eğitimi sonlandırırsanız bu içerik tamamlanmamış olarak kaydedilecektir.</small>' : 'Videoya kaldığınız yerden devam edebilir ya da eğitimi sonlandırabilirsiniz.',
typeAnimated: true,
onContentReady: function () {
$(document).on("mousedown touchstart", function () {
$(document).find(".jconfirm-bg").css("background-color", "rgba(54,70,93,0.25)");
});
$(document).on("mouseup touchstart", function () {
$(document).find(".jconfirm-bg").css("background-color", "rgba(54,70,93,0.95)");
});
},
buttons: {
basla: {
text: '<i class="fa fa-play" style="margin-right:10px;"></i> Devam Et',
btnClass: 'btn-green',
action: function () {
player.play();
//SaveState(false);
}
},
kapat: {
text: '<i class="fa fa-times" style="margin-right:10px;"></i> Bitir',
btnClass: 'btn-red',
action: function () {
if (completedbefore == true) {
window.location.href = $("#routebase").val() + "Calisan/EgitimDetay/" + icerik.EgitimKodu + '?isyerikodu='+$("#pinfo").attr("data-isyerikodu");
} else {
SaveState(true);
}
}
},
gizle: {
text: '<i class="fa fa-eye-slash" style="margin-right:10px;"></i> Gizle',
btnClass: 'btn-red',
action: function () {
$(".jconfirm").remove();
}
}
}
});
}
}
});
//End event
player.on('ended', event => {
if (((currenttime == kontrolegitimiceriksure || currenttime == icerik.KontrolKaldigiSure) && cevaplanankontrolegitimicerik.length !== 0 && cevaplanankontrolegitimicerik.indexOf(kontrolegitimicerik)) == -1 || ((currenttime == etkilesimliegitimiceriksure || currenttime == icerik.KontrolKaldigiSure) && cevaplananetkilesimliegitimicerik.length !== 0 && cevaplananetkilesimliegitimicerik.indexOf(etkilesimliegitimicerik) == -1)) {
$("#video-filigram").removeClass("hidden");
player.pause();
SaveState(false);
$(".jconfirm").remove();
} else if (currenttime != icerik.KontrolKaldigiSure) {
LessonEnd(/*otomatikdevamet:*/true);
}
});
$(window).on('blur', windowBlurred);
$(window).on('focus', windowFocused);
$(document).on("contextmenu", function () {
return false;
});
$(document).on("click", "#ksCevapla", function () {
var soru = kontrolsorular.find(x => x.ID == "" + aktifsoru);
var vc = $('input[name="ks"]:checked').val();
var msg = "";
if (typeof vc == "undefined") {
alert("Lütfen soruyu cevaplayınız.");
} else if (vc == soru.DOGRUCEVAP) {
msg = "Tebrikler. Doğru Cevap.";
$("#ksmsg").html(msg).removeClass("text-red").addClass("text-green");
soru.SORULDU = true;
soru.VERILENCEVAP = vc;
setTimeout(function () {
HideKs();
player.play();
}, 2000);
} else {
msg = "Üzgünüz. Yanlış cevap.";
msg += soru.AKSIYONZAMAN != "" ? " İlgili bölüme yönlendiriliyor..." : "";
$("#ksmsg").html(msg).removeClass("text-green").addClass("text-red");
soru.SORULDU = true;
soru.VERILENCEVAP = vc;
setTimeout(function () {
HideKs();
if (soru.AKSIYONZAMAN != "") {
player.currentTime = Number(soru.AKSIYONZAMAN);
player.play();
}
}, 3000);
}
});
});
function ShowWelcome() {
//Show welcome message
$.confirm({
theme: 'supervan',
closeIcon: false,
title: 'Sn. ' + icerik.CalisanAdSoyad,
content: '<i class="fa fa-spinner fa-spin"></i> Ders içeriğiniz hazırlanıyor...',
typeAnimated: true,
onContentReady: function () {
if (isios) {
ShowButtons();
}
$(document).on("mousedown touchstart", function () {
$(document).find(".jconfirm-bg").css("background-color", "rgba(54,70,93,0.25)");
});
$(document).on("mouseup touchstart", function () {
$(document).find(".jconfirm-bg").css("background-color", "rgba(54,70,93,0.95)");
});
},
buttons: {
basla: {
text: '<i class="fa fa-play" style="margin-right:10px;"></i> Başla',
btnClass: 'btn-green basla actionbtn hidden',
action: function () {
if (icerik.Tamamlandi == false) {
console.log("start lesson");
player.play();
} else {
player.currentTime = (icerik.KontrolKaldigiSure == 0) ? 0 : icerik.KontrolKaldigiSure;
player.play();
}
}
},
kapat: {
text: '<i class="fa fa-times" style="margin-right:10px;"></i> Vazgeç',
btnClass: 'btn-red vazgec actionbtn hidden',
action: function () {
window.location.href = $("#routebase").val() + "Calisan/EgitimDetay/" + icerik.EgitimKodu + '?isyerikodu=' + $("#pinfo").attr("data-isyerikodu");
}
}
}
});
}
function ShowButtons() {
player.currentTime = (icerik.KontrolKaldigiSure == 0) ? icerik.KaldigiSure : icerik.KontrolKaldigiSure;
icerik.ToplamSure = parseInt(player.duration);
var dersInfo = '<b>' + icerik.EgitimAdi + '</b> eğitiminin<br/> <b> ' + icerik.DokumanTanimi + '</b> başlıklı içeriği hazırlandı. <br/><br/> <small><i class="fa fa-warning"></i> UYARI <br/> Video tamamlanmadan çıkmanız halinde eğitiminiz tamamlanmamış olarak kaydedilecektir.</small>';
if (completedbefore) {
dersInfo = '<div><b>' + icerik.EgitimAdi + '</b> eğitiminin<br/> <b> ' + icerik.DokumanTanimi + '</b> başlıklı içeriğini daha önce tamamladınız.<br/><br/> Yeniden izlemek için lütfen Başla butonuna basınız.</div>';
}
$(document).find(".jconfirm-content").html(dersInfo);
$(document).find(".actionbtn").removeClass("hidden");
}
function LessonEnd(otomatikdevamet = false) {
icerik.Tamamlandi = true;
icerik.KaldigiSure = parseInt(player.duration);
if (otomatikdevamet == true) {
SaveState(false);
var url = '/Calisan/VideoViewer/?dk=b0af9b9e-dfdb-4651-8305-bf5891c29633&ek=1ae2b8e4-971f-4025-a8e2-97cbc60989bd&cei=87e3b3d1-1b0e-4fcd-a5ba-2b803c93ac27&cek=dad47501-bdd3-4275-a01e-631e77ecc242&isyerikodu=AEFC7F5C-7FA2-4A9E-83A3-6FED40C4A829';
if (url != "" && url != null && url != undefined) {
var decodedurl = url.replace(/&/g, '&');
window.location.href = decodedurl;
} else {
LessonEnd();
}
} else {
$.confirm({
theme: 'supervan',
closeIcon: false,
title: 'İçerik Tamamlandı',
content: completedbefore == false ? 'Tebrikler. Eğitim içeriğini başarıyla tamamladınız.' : 'Video sona erdi.',
typeAnimated: true,
onOpenBefore: function () {
var SonrakiIcerikDurumu = "1";
if (SonrakiIcerikDurumu != "1") {
$(".sonrakiislemler").remove();
}
},
buttons: {
basla: {
text: '<i class="fa fa-play" style="margin-right:10px;"></i> Eğitim Sayfasına Dön',
btnClass: 'btn-green',
action: function () {
if (completedbefore == true) {
window.location.href = $("#routebase").val() + "Calisan/EgitimDetay/" + icerik.EgitimKodu + '?isyerikodu=' + $("#pinfo").attr("data-isyerikodu");
} else {
SaveState(true);
}
}
},
kapat: {
text: '<i class="fa fa-undo" style="margin-right:10px;"></i> Yeniden İzle',
btnClass: 'btn-green',
action: function () {
player.currentTime = 0;
player.play();
}
},
sonraki: {
text: '<i id="sonrakiislemicon" class="fa fa-step-forward" style="margin-right:10px;"></i> <span id="sonrakiislem"> Sonraki İçerik </span>',
btnClass: 'btn-green sonrakiislemler',
action: function () {
var url = '/Calisan/VideoViewer/?dk=b0af9b9e-dfdb-4651-8305-bf5891c29633&ek=1ae2b8e4-971f-4025-a8e2-97cbc60989bd&cei=87e3b3d1-1b0e-4fcd-a5ba-2b803c93ac27&cek=dad47501-bdd3-4275-a01e-631e77ecc242&isyerikodu=AEFC7F5C-7FA2-4A9E-83A3-6FED40C4A829';
var decodedurl = url.replace(/&/g, '&');
window.location.href = decodedurl;
}
}
}
});
}
}
var kaldigimsure = 0;
function windowBlurred() {
kaldigimsure = player.currentTime.toFixed(0);
if (videoarkaplandaoynat == false) {
player.pause();
//if (kaldigimsure > player.currentTime.toFixed(0)) {
// setTimeout(function () {
// window.location.href = $("#routebase").val() + "Calisan/EgitimDetay/" + icerik.EgitimKodu + '?isyerikodu=' + $("#pinfo").attr("data-isyerikodu");
// }, 750);
//}
}
}
function windowFocused() {
if (videoarkaplandaoynat == false) {
//if (kaldigimsure > player.currentTime.toFixed(0)) {
// setTimeout(function () {
// window.location.href = $("#routebase").val() + "Calisan/EgitimDetay/" + icerik.EgitimKodu + '?isyerikodu=' + $("#pinfo").attr("data-isyerikodu");
// }, 750);
//}
}
}
function SaveState(exit) {
if (completedbefore == false) {
var maxduration = parseInt(player.duration);
var percentage = 100 * icerik.KaldigiSure / maxduration;
icerik.TamamlanmaDurum = percentage >= 100 ? 100 : parseInt(percentage);
var currentorder = savetries.length;
var savetry = {
order: currentorder,
time: moment().format("DD.MM.YYYY HH:mm:ss"),
duration: currenttime,
state: false,
error: ""
};
savetries.push(savetry);
icerik.IsyeriKodu = $("#pinfo").attr("data-isyerikodu");
icerik.GecenSure = gecensure;
$.ajax({
url: '/Calisan/VideoDurumKaydet',
type: 'POST',
dataType: 'json',
data: icerik,
success: function (data) {
if (data.state) {
savetries[currentorder].state = true;
if (completedbefore == false && icerik.Tamamlandi == true) {
completedbefore = true;
}
if (exit) {
if (data.tumiceriktamam == true && data.sonsinavotomatikbaslat == true) {
alertify.success("Eğitim sınavına yönlendiriliyorsunuz. Lütfen bekleyin.");
setTimeout(function () {
window.location.href = $("#routebase").val() + data.sonsinavhref;
}, 750);
} else {
alertify.success("Eğitim durumu kaydedildi. Lütfen bekleyin.");
setTimeout(function () {
window.location.href = $("#routebase").val() + "Calisan/EgitimDetay/" + icerik.EgitimKodu + '?isyerikodu=' + $("#pinfo").attr("data-isyerikodu");
}, 750);
}
} else {
if (data.tumiceriktamam == true && data.sonsinavotomatikbaslat == true) {
alertify.success("Eğitim sınavına yönlendiriliyorsunuz. Lütfen bekleyin.");
setTimeout(function () {
window.location.href = $("#routebase").val() + data.sonsinavhref;
}, 750);
}
}
} else {
savetries[currentorder].state = false;
savetries[currentorder].error = data.message;
if (data.state == false) {
alertify.error(data.message);
setTimeout(function () {
window.location.href = $("#routebase").val() + "Calisan/EgitimDetay/" + icerik.EgitimKodu + '?isyerikodu=' + $("#pinfo").attr("data-isyerikodu");
}, 1500);
What can we do about it? Please help me. Thank you.

Create a javascript object

I would say I am fairly decent with javascript and jQuery, well, enough to get the job done and done pretty well.
I do however lack a deep understanding of js.
I have created some functions for highlighting table elements.
ctrl+click toggles selections
shift+click+drag highlights selection
My question does not pertain to whether or not my implementation is the best way or not but ...
How do I abstract this functionality so I can add this functionality to any table. Like if I add more highlighting features and such and put this in its own .js file. How would I attach it to any html table?
Sorry if this has already been answered, but I could not think of what to search for.
Thank you.
****Newest Code****
This code is in its own .js file and is attached to my table.
All the current functionality is there. The only thing I am weary of is the .off() functions. In my case, I am reloading new tables.... as I type this, I realize I should just empty the tr's from the table instead of recreating a new table all the time, then I could get rid of the .off() calls.
$.fn.addEvents = function(obj)
{
console.log("Adding events to table");
var properties = $.extend(true,
{
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
mousestartindex: 0,
mouseenterindex: 0,
mouseleaveindex: 0,
trajectory: null,
tmptrajectory: null
}, obj || {});
$(document)
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
})
.off("keyup")
.on("keyup", function(e)
{
if(e.which == 16)
{
properties.shifting = false;
}
if(e.which == 17)
{
properties.ctrling = false;
}
})
.off("keydown")
.on("keydown", function(e)
{
if(e.which == 16)
{
properties.shifting = true;
}
if(e.which == 17)
{
properties.ctrling = true;
}
if($(this).find('tr.selected').length > 0)
{
switch(e.which)
{
//case 37: // left
//break;
case 38: // up
var index = $(this).find('tr.selected').index();
if(index > 0)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + index + ')').addClass('selected');
$(this).find('tr:eq(' + index + ') td').addClass('selected');
}
break;
//case 39: // right
//break;
case 40: // down
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 2)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + (index+2) + ')').addClass('selected');
$(this).find('tr:eq(' + (index+2) + ') td').addClass('selected');
}
break;
case 117: // f6
var index = $(this).find('tr.selected').index();
if(index > 0)
{
....
}
break;
case 118: // f7
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 1)
{
....
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
return;
});
return $(this)
.off('click')
.off('contextmenu')
.on('click', function()
{
if(!properties.ctrling && !properties.shifting)
{
$('#datatablebody tr, #datatablebody tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(properties.ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(properties.ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
})
.on('contextmenu', function(ev)
{
ev.preventDefault();
$('#datatablebody tr, #datatablebody tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
showContextMenuTR($(this).closest('tr').attr('id'), ev.clientX, ev.clientY);
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
properties.mousing = true;
properties.mousestartindex = $(this).index();
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
})
.off('mouseenter')
.on('mouseenter', function(e)
{
properties.mouseenter = e.clientY;
properties.mouseenterindex = $(this).index();
if(properties.tmptrajectory === properties.trajectory)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
})
.off('mouseleave')
.on('mouseleave', function(e)
{
properties.mouseleave = e.clientY;
if(properties.shifting && properties.mousing)
{
properties.tmptrajectory = properties.mouseenter - properties.mouseleave < 0?1:-1;
}
if(properties.trajectory != null && properties.tmptrajectory !== properties.trajectory && $(this).index() !== properties.mousestartindex)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
if(properties.shifting && properties.mousing)
{
if(properties.trajectory == null)
{
properties.trajectory = properties.tmptrajectory;
}
else if(properties.tmptrajectory !== properties.trajectory && $(this).index() === properties.mousestartindex)
{
properties.trajectory = properties.tmptrajectory;
}
}
})
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
});
}
function multiselectrow(obj)
{
if($(obj).hasClass('selected'))
{
$(obj).removeClass('selected');
$(obj).find('td').removeClass('selected');
}
else
{
$(obj).addClass('selected');
$(obj).find('td').addClass('selected');
}
}
you can wrap all this in a function since you have some local variables related to individual selection
$.fn.addEvents = function(obj) {
var properties = $.extend(true, {
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
trajectory: null
}, obj || {});
return $(this)
.off('click')
.off('contextmenu')
.on('click', function() {
.....
})
.on('mouseleave', function(e) {
//rename your local variables with `properties.` prefix
properties.mouseleave = e.clientY;
if (properties.shifting && properties.mousing) {
tmptrajectory = properties.mouseenter - properties.mouseleave < 0 ? 1 : -1;
}
if ($(this).hasClass('selected') && properties.shifting && properties.mousing && properties.trajectory != null && properties.trajectory != tmptrajectory) {
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
....
});
}
usage
$('#datatablebody tr').addEvents({ shifting: false, ctrling: true }); //custom settings
$('#someother tr').addEvents(); //default settings
you could add that functionality to a class and add that class to the tables you want to affect...
Here I create the class .myTableBeh and all tables with that class will have the behaviour you programmed.
var shifting = false;
var ctrling = false;
var mousing = false;
var mouseenter = 0;
var mouseleave = 0;
var trajectory = null;
$('.myTableBeh tr')
.off('click')
.off('contextmenu')
.on('click', function()
{
if(!ctrling)
{
$('.myTableBeh tr, .myTableBeh tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
})
.on('contextmenu', function(ev)
{
ev.preventDefault();
$('.myTableBeh tr, .myTableBeh tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
showContextMenuTR($(this).closest('tr').attr('id'), ev.clientX, ev.clientY);
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
mousing = true;
multiselectrow($(this));
})
.off('mouseenter')
.on('mouseenter', function(e)
{
mouseenter = e.clientY;
multiselectrow($(this));
})
.off('mouseleave')
.on('mouseleave', function(e)
{
mouseleave = e.clientY;
if(shifting && mousing)
{
tmptrajectory = mouseenter - mouseleave < 0?1:-1;
}
if($(this).hasClass('selected') && shifting && mousing && trajectory != null && trajectory != tmptrajectory)
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
if(shifting && mousing && trajectory == null)
{
trajectory = tmptrajectory;
}
})
.off('mouseup')
.on('mouseup', function(e)
{
mousing = false;
trajectory = null;
multiselectrow($(this));
});
Thanks to the answer from #JAG I was able to create a nice add on to any HTML table that handles highlighting.
Check out the fiddle for the working version and please use it if you find it helpful or useful for your site.
You can even implement keys to move the tr position up or down in the table. I removed my implementation because it was specific to the project I am working on.
I made it so you have to mouse over the table in order to interact with it and mouse leave to un-focus it.
https://jsfiddle.net/kwj74kg0/2/
//Add the events simply by running this
$('#dtable tr').addEvents(0);
/**
* This add on can be applied and customized to any html tr set i.e. $('#tableid tr').addEvents()
* It will add highlighting capability to the table.
*
* Single click highlight tr
* Click -> Shift + click highlight/toggle range
* Shift+MouseDown+Drag highlight/toggle range
* Ctrl+Click toggle item
*
*
* #author Michaela Ervin
*
* #param tabindex
*
* Help from JAG on http://stackoverflow.com/questions/39022116/create-a-javascript-object
*/
$.fn.addEvents = function(tabindex)
{
console.log("Adding events to table");
var properties = $.extend(true,
{
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
mousestartindex: 0,
mouseenterindex: null,
mouseleaveindex: null,
trajectory: null,
tmptrajectory: null
}, {});
/**
* Add events to closest table.
*/
$(this)
.closest('table')
.attr('tabindex', tabindex)
.off('mouseenter')
.on('mouseenter', function()
{
$(this).focus();
})
.off('mouseleave')
.on('mouseleave', function()
{
$(this).blur();
properties.mousing = false;
properties.trajectory = null;
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
properties.mouseintermediateindex = null;
})
.off("keyup")
.on("keyup", function(e)
{
if(e.which == 16)
{
properties.shifting = false;
}
if(e.which == 17)
{
properties.ctrling = false;
}
})
.off("keydown")
.on("keydown", function(e)
{
if(e.which == 16)
{
properties.shifting = true;
}
if(e.which == 17)
{
properties.ctrling = true;
}
if($(this).find('tr.selected').length > 0)
{
switch(e.which)
{
//case 37: // left
//break;
case 38: // up
var index = $(this).find('tr.selected').index();
if(index > 0)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + index + ')').addClass('selected');
$(this).find('tr:eq(' + index + ') td').addClass('selected');
}
break;
//case 39: // right
//break;
case 40: // down
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 2)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + (index+2) + ')').addClass('selected');
$(this).find('tr:eq(' + (index+2) + ') td').addClass('selected');
}
break;
case 117: // f6
var index = $(this).find('tr.selected').index();
if(index > 0)
{
//Function to move tr 'up'.
}
break;
case 118: // f7
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 1)
{
//Function to move tr 'down'.
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
return;
});
/**
* Add tr specific events
*/
return $(this)
.off('click')
.on('click', function()
{
if(!properties.shifting && properties.mouseenterindex != null)
{
properties.mouseenterindex = null;
properties.mousing = false;
}
if(!properties.ctrling && !properties.shifting && properties.mouseenterindex == null)
{
$(this).parent().find('tr').removeClass('selected');
$(this).parent().find('tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(properties.ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(properties.ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
if(properties.mouseenterindex == null)
{
properties.mouseenterindex = $(this).index();
}
else if(properties.shifting && properties.mouseenterindex != null)
{
properties.mouseleaveindex = $(this).index();
highlightRange($(this).parent(), properties.mouseenterindex, properties.mouseleaveindex, properties.mouseenterindex);
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
}
})
.off('contextmenu')
.on('contextmenu', function(ev)
{
ev.preventDefault();
$(this).parent().find('tr').removeClass('selected');
$(this).parent().find('tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
//Put your context menu here
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
properties.mousing = true;
properties.mousestartindex = $(this).index();
if(properties.shifting && properties.mousing && properties.mouseenterindex == null)
{
multiselectrow($(this));
}
})
.off('mouseenter')
.on('mouseenter', function(e)
{
properties.mouseenter = e.clientY;
if(properties.tmptrajectory === properties.trajectory)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
})
.off('mouseleave')
.on('mouseleave', function(e)
{
properties.mouseleave = e.clientY;
if(properties.shifting && properties.mousing)
{
properties.tmptrajectory = properties.mouseenter - properties.mouseleave < 0?1:-1;
}
if(properties.trajectory != null && properties.tmptrajectory !== properties.trajectory && $(this).index() !== properties.mousestartindex)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
if(properties.shifting && properties.mousing)
{
if(properties.trajectory == null)
{
properties.trajectory = properties.tmptrajectory;
}
else if(properties.tmptrajectory !== properties.trajectory && $(this).index() === properties.mousestartindex)
{
properties.trajectory = properties.tmptrajectory;
}
}
})
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
if(!properties.shifting)
{
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
}
});
}
function multiselectrow(obj)
{
if($(obj).hasClass('selected'))
{
$(obj).removeClass('selected');
$(obj).find('td').removeClass('selected');
}
else
{
$(obj).addClass('selected');
$(obj).find('td').addClass('selected');
}
}
function highlightRange(obj, start, end, mouseenterindex)
{
if(start < end)
{
for(var i=start; i<=end; i+=1)
{
if(i !== mouseenterindex)
{
multiselectrow($(obj).find('tr').eq(i));
}
}
}
else
{
for(var i=start; i>=end; i-=1)
{
if(i !== mouseenterindex)
{
multiselectrow($(obj).find('tr').eq(i));
}
}
}
}

Autocomplete cities similar to kayak.com from Postgresql with PHP and JS

I would like to have a input where, when the user type in anything all the cities available appear to him. Something like the functionality in kayak.com
So if the user type in the letter M, all the cities starting with M will show like in the picture below.
So I have the following code that works but only for the options provided under var choices:
<form onsubmit="$('#hero-demo').blur();return false;" class="pure-form" style="border-top: 1px solid #eee;border-bottom:1px solid #eee;background:#fafafa;margin:30px 0;padding:20px 10px;text-align:center">
<input id="hero-demo" autofocus type="text" name="q" placeholder="Programming languages ..." style="width:100%;max-width:600px;outline:0">
</form>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="jquery.auto-complete.js"></script>
<script>
$(function(){
$('#hero-demo').autoComplete({
minChars: 1,
source: function(term, suggest){
term = term.toLowerCase();
var choices = ['Birmingham', 'Dallas', 'Houston','New York', 'San Francisco'];
var suggestions = [];
for (i=0;i<choices.length;i++)
if (~choices[i].toLowerCase().indexOf(term)) suggestions.push(choices[i]);
suggest(suggestions);
}
});
});
</script>
Then I have this PHP code to pull all my cities from my postgresql database:
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT * FROM cities";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
//This is just to print out all the cities I have in my database with their countries
while($myrow = pg_fetch_assoc($result)) {
$city = $myrow[city];
$country = $myrow[country];
echo $city;
echo $country;
echo '<br>';
}
?>
I have 2 questions:
How can I do to substitute the values in var choices for the values retrieve from my postgreqsl database with $query = "SELECT * FROM cities";?
How can I do to have also added the country so if there are two cities named the same in different countries or States all show up: Example:
If I type in Tole --> I'll see:
Toledo, Spain
Toledo, OH
Toledo, OR
Toledo, IA
Toledo, WA
Toledo, IL
Thank you so much
Here is the code from jquery.auto-complete.js:
(function($){
$.fn.autoComplete = function(options){
var o = $.extend({}, $.fn.autoComplete.defaults, options);
// public methods
if (typeof options == 'string') {
this.each(function(){
var that = $(this);
if (options == 'destroy') {
$(window).off('resize.autocomplete', that.updateSC);
that.off('blur.autocomplete focus.autocomplete keydown.autocomplete keyup.autocomplete');
if (that.data('autocomplete'))
that.attr('autocomplete', that.data('autocomplete'));
else
that.removeAttr('autocomplete');
$(that.data('sc')).remove();
that.removeData('sc').removeData('autocomplete');
}
});
return this;
}
return this.each(function(){
var that = $(this);
// sc = 'suggestions container'
that.sc = $('<div class="autocomplete-suggestions '+o.menuClass+'"></div>');
that.data('sc', that.sc).data('autocomplete', that.attr('autocomplete'));
that.attr('autocomplete', 'off');
that.cache = {};
that.last_val = '';
that.updateSC = function(resize, next){
that.sc.css({
top: that.offset().top + that.outerHeight(),
left: that.offset().left,
width: that.outerWidth()
});
if (!resize) {
that.sc.show();
if (!that.sc.maxHeight) that.sc.maxHeight = parseInt(that.sc.css('max-height'));
if (!that.sc.suggestionHeight) that.sc.suggestionHeight = $('.autocomplete-suggestion', that.sc).first().outerHeight();
if (that.sc.suggestionHeight)
if (!next) that.sc.scrollTop(0);
else {
var scrTop = that.sc.scrollTop(), selTop = next.offset().top - that.sc.offset().top;
if (selTop + that.sc.suggestionHeight - that.sc.maxHeight > 0)
that.sc.scrollTop(selTop + that.sc.suggestionHeight + scrTop - that.sc.maxHeight);
else if (selTop < 0)
that.sc.scrollTop(selTop + scrTop);
}
}
}
$(window).on('resize.autocomplete', that.updateSC);
that.sc.appendTo('body');
that.sc.on('mouseleave', '.autocomplete-suggestion', function (){
$('.autocomplete-suggestion.selected').removeClass('selected');
});
that.sc.on('mouseenter', '.autocomplete-suggestion', function (){
$('.autocomplete-suggestion.selected').removeClass('selected');
$(this).addClass('selected');
});
that.sc.on('mousedown click', '.autocomplete-suggestion', function (e){
var item = $(this), v = item.data('val');
if (v || item.hasClass('autocomplete-suggestion')) { // else outside click
that.val(v);
o.onSelect(e, v, item);
that.sc.hide();
}
return false;
});
that.on('blur.autocomplete', function(){
try { over_sb = $('.autocomplete-suggestions:hover').length; } catch(e){ over_sb = 0; } // IE7 fix :hover
if (!over_sb) {
that.last_val = that.val();
that.sc.hide();
setTimeout(function(){ that.sc.hide(); }, 350); // hide suggestions on fast input
} else if (!that.is(':focus')) setTimeout(function(){ that.focus(); }, 20);
});
if (!o.minChars) that.on('focus.autocomplete', function(){ that.last_val = '\n'; that.trigger('keyup.autocomplete'); });
function suggest(data){
var val = that.val();
that.cache[val] = data;
if (data.length && val.length >= o.minChars) {
var s = '';
for (var i=0;i<data.length;i++) s += o.renderItem(data[i], val);
that.sc.html(s);
that.updateSC(0);
}
else
that.sc.hide();
}
that.on('keydown.autocomplete', function(e){
// down (40), up (38)
if ((e.which == 40 || e.which == 38) && that.sc.html()) {
var next, sel = $('.autocomplete-suggestion.selected', that.sc);
if (!sel.length) {
next = (e.which == 40) ? $('.autocomplete-suggestion', that.sc).first() : $('.autocomplete-suggestion', that.sc).last();
that.val(next.addClass('selected').data('val'));
} else {
next = (e.which == 40) ? sel.next('.autocomplete-suggestion') : sel.prev('.autocomplete-suggestion');
if (next.length) { sel.removeClass('selected'); that.val(next.addClass('selected').data('val')); }
else { sel.removeClass('selected'); that.val(that.last_val); next = 0; }
}
that.updateSC(0, next);
return false;
}
// esc
else if (e.which == 27) that.val(that.last_val).sc.hide();
// enter or tab
else if (e.which == 13 || e.which == 9) {
var sel = $('.autocomplete-suggestion.selected', that.sc);
if (sel.length && that.sc.is(':visible')) { o.onSelect(e, sel.data('val'), sel); setTimeout(function(){ that.sc.hide(); }, 20); }
}
});
that.on('keyup.autocomplete', function(e){
if (!~$.inArray(e.which, [13, 27, 35, 36, 37, 38, 39, 40])) {
var val = that.val();
if (val.length >= o.minChars) {
if (val != that.last_val) {
that.last_val = val;
clearTimeout(that.timer);
if (o.cache) {
if (val in that.cache) { suggest(that.cache[val]); return; }
// no requests if previous suggestions were empty
for (var i=1; i<val.length-o.minChars; i++) {
var part = val.slice(0, val.length-i);
if (part in that.cache && !that.cache[part].length) { suggest([]); return; }
}
}
that.timer = setTimeout(function(){ o.source(val, suggest) }, o.delay);
}
} else {
that.last_val = val;
that.sc.hide();
}
}
});
});
}
$.fn.autoComplete.defaults = {
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};
}(jQuery));
I really like this plugin called awesomeplete. Light, easy to use. It is very flexible with how you attach the options.

jQuery: How can I put two of these elements on the same page?

I am using the following script, but if I put more than 1 occurrence on the same page, it breaks. I am trying to get it to where I can put multiple carousels on the same page.
HTML:
<div class="carousel_outer">
<div class="portfolio-carousel horizontal">
<div class="carousel" id="carousel1">
<div class="carousel_container carousel1">
<ul class="portfolio-wrap carousel1">
<li><a class="gall_thumb" href="#" title="First Pic"><img src="#" alt="First Pic" /></a></li>
<li><a class="gall_thumb" href="#" title="Second Pic"><img src="#" alt="Second Pic" /></a></li>
</ul>
</div>
<a class="carousel_prev" href="#">Previous</a>
<a class="carousel_next" href="#">Next</a>
</div>
</div>
</div>
Javascript on the page:
$('.carousel').mycarousel({
delay: 150,
fade:300,
slide: 700,
effect:'slide',
orientation:'horizontal',
loop: false,
autoplay: false
});
And the actual carousel javascript:
(function ($) {
$.fn.extend({
mycarousel: function (options) {
var defaults = {
delay: 150,
fade: 300,
slide: 500,
effect: "fade",
orientation: "horizontal",
captionFade: 150,
loop: false,
autoplay: true,
time: 3000
};
var options = $.extend(defaults, options);
return this.each(function () {
var o = options;
var carousel = this;
$carousel_container = $(carousel).find(".carousel_container");
$li = $(carousel).find(".carousel_container ul li");
var visible_width = parseInt($carousel_container.css("width"), 10);
var visible_height = parseInt($carousel_container.css("height"), 10);
var number_items = $li.size();
var item_width = parseInt($li.css("width"), 10);
var item_height = parseInt($li.css("height"), 10);
var item_marginRight = parseInt($li.css("marginRight"), 10);
var item_marginLeft = parseInt($li.css("marginLeft"), 10);
var item_marginTop = parseInt($li.css("marginTop"), 10);
var item_marginBottom = parseInt($li.css("marginBottom"), 10);
if (o.orientation == "horizontal") {
var visible_items = Math.ceil(visible_width / (item_width + item_marginRight + item_marginLeft));
} else {
var visible_items = Math.ceil(visible_height / (item_height + item_marginTop + item_marginBottom));
}
var slides = Math.ceil(number_items / visible_items);
$float_easing = "easeInOutQuart";
function set_item_classes_visibility() {
$li.each(function (index) {
var class_number = Math.floor((index + visible_items) / visible_items);
$(this).addClass("visible_" + class_number);
if (class_number == "1") {
$(this).css("display", "block");
$(this).find(".inner").css("display", "block");
} else {
$(this).css("display", "none");
$(this).find(".inner").css("display", "none");
}
});
}
set_item_classes_visibility();
function set_next_prev_classes() {
var visible_item_class = $(carousel).find(".carousel_container ul li:visible").attr("class");
var visible_id = visible_item_class.split("_");
if (!o.loop) {
if (visible_id[1] == "1") {
$(".carousel_prev").addClass("disable");
} else {
$(".carousel_prev").removeClass("disable");
}
if (visible_id[1] == slides) {
$(".carousel_next").addClass("disable");
} else {
$(".carousel_next").removeClass("disable");
}
}
}
set_next_prev_classes();
function set_item_position() {
$li.each(function () {
$(this).css("display", "none");
$(this).css("position", "absolute");
if (o.orientation == "horizontal") {
$(this).css("top", "0");
$(this).css("left", visible_width + parseInt($carousel_container.css("paddingLeft")) + parseInt($carousel_container.css("paddingRight")), 10);
} else {
if (o.orientation == "vertical") {
$(this).css("left", "0");
$(this).css("top", visible_height + parseInt($carousel_container.css("paddingTop")) + parseInt($carousel_container.css("paddingBottom")), 10);
}
}
});
$carousel_container.find("li.visible_1").each(function (index) {
$(this).css("display", "block");
if (o.orientation == "horizontal") {
var left_position = (index * (item_width + item_marginRight + item_marginLeft)) + parseInt($carousel_container.css("paddingLeft"), 10);
$(this).css("left", left_position);
} else {
if (o.orientation == "vertical") {
var top_position = (index * (item_height + item_marginTop + item_marginBottom)) + parseInt($carousel_container.css("paddingTop"), 10);
$(this).css("top", top_position);
}
}
});
}
if (o.effect == "slide") {
set_item_position();
}
function show_next_prev(method) {
function show_items_fade(id) {
var next_class_name = "visible_" + id;
$carousel_container.find("li." + next_class_name).css("display", "block");
$carousel_container.find("li." + next_class_name).each(function (index) {
var delay = (index) * o.delay;
if (method == "prev") {
var delay = ((visible_items - 1) - index) * o.delay;
}
var index_item = (index + 1);
$(this).find(".inner").delay(delay).fadeIn(o.fade, function () {
if (index_item == visible_items || id == slides) {
set_next_prev_classes();
}
});
});
}
function show_items_slide(id) {
var next_class_name = "visible_" + id;
$carousel_container.find("li." + next_class_name + " .inner").css("display", "block");
$carousel_container.find("li." + next_class_name).each(function (index) {
$(this).css("display", "block");
var delay = (index) * o.delay;
if (method == "prev") {
var delay = ((visible_items - 1) - index) * o.delay;
}
var index_item = (index + 1);
if (o.orientation == "horizontal") {
var left_position = (index * (item_width + item_marginRight + item_marginLeft)) + parseInt($carousel_container.css("paddingLeft"), 10);
$(this).delay(delay).animate({
left: left_position
}, o.slide, $float_easing, function () {
if (index_item == visible_items || id == slides) {
set_next_prev_classes();
}
});
} else {
if (o.orientation == "vertical") {
var top_position = (index * (item_height + item_marginTop + item_marginBottom)) + parseInt($carousel_container.css("paddingTop"), 10);
$(this).delay(delay).animate({
top: top_position
}, o.slide, $float_easing, function () {
if (index_item == visible_items || id == slides) {
set_next_prev_classes();
}
});
}
}
});
}
var visible_item_class = $carousel_container.find("li:visible").attr("class");
visible_id = visible_item_class.split("_");
var next_id = parseInt(visible_id[1], 10) + 1;
var prev_id = parseInt(visible_id[1], 10) - 1;
if (visible_id[1] == 1) {
prev_id = slides;
}
if (visible_id[1] == slides) {
next_id = 1;
}
switch (o.effect) {
case "fade":
$carousel_container.find("li:visible").each(function (index) {
var delay = (index) * o.delay;
var index_item = (index + 1);
var last_item = $carousel_container.find("li." + visible_item_class).size();
if (method == "prev") {
delay = ((visible_items - 1) - index) * o.delay;
last_item = 1;
}
$(this).find(".inner").delay(delay).fadeOut(o.fade, function () {
if (index_item == last_item) {
$("li." + visible_item_class).css("display", "none");
if (method == "next") {
show_items_fade(next_id);
} else {
if (method == "prev") {
show_items_fade(prev_id);
}
}
}
});
});
break;
case "slide":
$carousel_container.find("li.visible_" + prev_id).each(function (index) {
if (o.orientation == "horizontal") {
if (method == "next") {
var left_position = visible_width + parseInt($carousel_container.css("paddingLeft"), 10) + parseInt($carousel_container.css("paddingRight"), 10);
} else {
if (method == "prev") {
var left_position = "-" + item_width + "px";
}
}
$(this).css("left", left_position);
} else {
if (o.orientation == "vertical") {
if (method == "next") {
var top_position = visible_height + parseInt($carousel_container.css("paddingTop"), 10) + parseInt($carousel_container.css("paddingBottom"), 10);
} else {
if (method == "prev") {
var top_position = "-" + item_height + "px";
}
}
$(this).css("top", top_position);
}
}
});
$carousel_container.find("li." + visible_item_class).each(function (index) {
var delay = (index) * o.delay;
var zindex = index + 10;
var index_item = (index + 1);
var last_item = $carousel_container.find("li." + visible_item_class).size();
if (method == "prev") {
delay = ((visible_items - 1) - index) * o.delay;
zindex = ((visible_items - 1) - index) + 10;
last_item = 1;
}
$(this).css("z-index", zindex);
if (o.orientation == "horizontal") {
if (method == "next") {
var left_position = "-" + item_width;
} else {
if (method == "prev") {
var left_position = visible_width + parseInt($carousel_container.css("paddingLeft"), 10) + parseInt($carousel_container.css("paddingRight"), 10);
}
}
$(this).delay(delay).animate({
left: left_position
}, o.slide, $float_easing, function () {
if (index_item == last_item) {
$("li." + visible_item_class).css("display", "none");
if (method == "next") {
show_items_slide(next_id);
} else {
if (method == "prev") {
show_items_slide(prev_id);
}
}
}
});
} else {
if (o.orientation == "vertical") {
if (method == "next") {
var top_position = "-" + item_height;
} else {
if (method == "prev") {
var top_position = visible_height + parseInt($carousel_container.css("paddingTop"), 10) + parseInt($carousel_container.css("paddingBottom"), 10);
}
}
$(this).delay(delay).animate({
top: top_position
}, o.slide, $float_easing, function () {
if (index_item == last_item) {
$("li." + visible_item_class).css("display", "none");
if (method == "next") {
show_items_slide(next_id);
} else {
if (method == "prev") {
show_items_slide(prev_id);
}
}
}
});
}
}
});
break;
}
}
if (o.autoplay) {
var interval = setInterval(function () {
var visible_item_class = $(carousel).find(".carousel_container ul li:visible").attr("class");
var visible_id = visible_item_class.split("_");
if (!o.loop) {
if (visible_id[1] == slides) {
clearInterval(interval);
} else {
show_next_prev("next");
}
} else {
show_next_prev("next");
}
}, o.time);
}
$(carousel).find(".carousel_next").click(function () {
clearInterval(interval);
show_next_prev("next");
return (false);
});
$(carousel).find(".carousel_prev").click(function () {
clearInterval(interval);
show_next_prev("prev");
return (false);
});
$li.hover(function () {
clearInterval(interval);
$(this).find(".caption").fadeIn(o.captionFade);
}, function () {
$(this).find(".caption").fadeOut(o.captionFade);
});
});
}
});
})(jQuery);
I'm thinking if there is some way I can identify each carousel with an ID and the script only executes things within each ID it would work, but I can't figure out how to get it done.
EDIT: I am getting the following js console error when I click a next/prev button: visible_item_class is undefined
Give them each an unique ID and call them by that.
$('#carousel1').mycarousel({
theid: $(this).attr('id'),
delay: 150,
fade:300,
slide: 700,
effect:'slide',
orientation:'horizontal',
loop: false,
autoplay: false
});
$('#carousel2').mycarousel({
theid: $(this).attr('id'),
delay: 150,
fade:300,
slide: 700,
effect:'slide',
orientation:'horizontal',
loop: false,
autoplay: false
});
On a side note is the following line necessary:
theid: $(this).attr('id')
I don't see it used anywhere in the carousel code.
Based on the function set_next_prev_classes in the plugin, the problem is probably that your 'next' and 'previous' buttons share a common class. (The plugin shouldn't do things this way, but there it is anyway.)
The solution should be as simple as giving each carousel DISTINCT class names for their 'next' and 'previous' buttons -- this can be as simple as appending the numbers 1 and 2 to each. (And then tell the plugin author that this approach is causing problems.)
Two ways to fix the problem.
Change the carousel code to take id of the div used as carousel , and carousel controls.
Copy the carousel code two times.Replace ".carousel" with "#Id1" in first and "#Id2" in second.Then the controls will be "#Id1_next", "#Id1_prev".
This is kind of hacky but cant help it.

Too much recursion Error in jQuery-1.7.2,is jquery error?

too much recursion error occur when i execute autocomplete.js today.Before today i never see like this error in jquery when i execute autocomplete.js. i am using jQuery 1.7.2
$(function(){
$("#search_text").keyup(function(e){
var sVal = $(this).val();
if(e.which == 27) {
$('#sresult_container').remove();
return;
}
if(e.which != 40 && e.which != 38) {
$("#search").removeAttr('disabled');
$.post('http://localhost/website/index.php/search/ajaxResults',{Search:sVal},function(data){
if(data != "$$$" && data.length != 0) {
var sData = data;
var flag1 = 0;
var flag2 = 0;
var tabindex = -1;
var aFarray = sData.split('$$$');
$('#sresult_container').remove();
var $sresult_container = $('<div id="sresult_container"></div>')
.css({'position':'absolute','border':'1px solid','background-color':'white','z-index':'10000000','width':'309px'});
for(var i=0;i<aFarray.length;i++) {
var a = aFarray[i].split('|||');
if(i == 0 && a[0] != "") {
flag1 = 1;
$pages = $('<div id="pages"></div>');
$text1 = $('<p></p>').css({'background-color':'silver','text-align':'center','padding':'3px'}).text("Pages");
$pages.append($text1);
if(a.length > 5) {
a = a.slice(0,5);
}
for(var j=1;j<a.length+1;j++) {
tabindex++;
$('<div>/div>').css({'padding':'5px','text-align':'center'}).text(a[j-1]).attr({'tabindex':tabindex,'class':'result'}).appendTo($pages);
}
}
if(i == 1 && a[0] != "") {
flag2 = 1;
$articles = $('<div id="articles"></div>');
$text2 = $("<p></p>").css({'background-color':'silver','text-align':'center','padding':'3px'}).text("Articles");
$articles.append($text2);
if(a.length > 5) {
a = a.slice(0,5);
}
for(var j=0;j<a.length;j++) {
tabindex++;
$('<div></div>').css({'padding':'5px','text-align':'center'}).text(a[j]).attr({'tabindex':tabindex,'class':'result'}).appendTo($articles);
}
}
}
if(flag1 == 0)
{
$articles.children().first().remove();
$div = $sresult_container.append($articles);
}else if(flag2 == 0)
{
$pages.children().first().remove();
$div = $sresult_container.append($pages);
}else
{
$div = $sresult_container.append($pages,$articles);
}
tabindex++;
$allresluts = $('<div id="allresults"></div>').css({'padding':'5px','text-align':'center','background-color':'#FBEE92','color':'#CC3333'}).text("See All Results").attr('tabindex',tabindex).appendTo($div);
var bottom = $('#search_text').offset();
var height = $('#search_text').outerHeight();
var left = bottom.left;
var top = bottom.top+height;
$div.offset({'top':top,'left':left});
$('body').append($div);
}
else
{
$('#sresult_container').remove();
$("#search").attr('disabled','true');
}
});
}
else
{
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
var tabindex = $con_div.length - 1;
if(e.which == 40)
{
$con_div.first().addClass("selected").focus();
var index = $con_div.first().index(this)+1;
$con_div.bind({
keydown: function(e) {
e.preventDefault();
var key = e.keyCode;
var target = $(e.target);
switch(key) {
case 38: // arrow up
if(index == 0)
{
index = tabindex+1;
}
$con_div[--index].focus();
break;
case 40: // arrow down
if(index > tabindex-1)
{
index = -1;
}
$con_div[++index].focus();
break;
case 13: //Enter
if(target.hasClass('result') == true)
{
$("#search_text").val(target.text());
$("#search").focus();
}
else
{
$('#search').click();
}
$div.remove();
break;
case 27://Esc
$div.remove();
$("#search_text").focus();
break;
}
},
focusin: function(e) {
$(e.currentTarget).addClass("selected");
},
focusout: function(e) {
$con_div.removeClass("selected");
$(e.currentTarget).removeClass("selected");
}
});
}
}
setTimeout(function()
{
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
$con_div.live({
click : function(e){
var $target = $(e.target);
if($target.hasClass('result') == true)
{
$("#search_text").val($target.text());
$("#search").focus();
}
else
{
$('#search').click();
}
$('#sresult_container').remove();
},
mouseover : function(e){
var $target = $(e.target);
if($target.hasClass('result') == true || $target.is('#allresults'))
{
$(e.target).css('cursor','pointer');
$con_div.removeClass("selected");
$(e.target).addClass("selected");
}
},
mouseout : function(){
$con_div.removeClass("selected");
}
});
}, 200 );
});
$("#search_text").blur(function(e){
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
if($con_div.hasClass('selected') != true)
{
$("#sresult_container").remove();
}
});
});
I got error in $('#search').click(); inside the code.

Categories