Make Multiple Pages Of a chat website using html/Js - javascript

i cant make a page for a different room (like chat rooms and you can pick what room you are chatting in) but it wont work, this is a code from another person but everyone is asking him to add rooms to his chat app so i tried doing it but im stuck, (note: the code is unchanged and his code works perfectly fine) here is a link to his chat app: https://replit.com/#NigelIsCoding/chat?v=1 , thank you for help :)
my main.js code:
$(function() {
var FADE_TIME = 150;
var TYPING_TIMER_LENGTH = 400;
var COLORS = [
'#94a19f', '#000000', '#7a7777', '#3b3b3b',
'#3c4544', '#7a7a7a', '#4f5251', '#575757',
'grey', 'darkgrey', 'black', '#404040'
];
var $window = $(window);
var $usernameInput = $('.usernameInput');
var $messages = $('.messages');
var $inputMessage = $('.inputMessage');
var $loginPage = $('.login.page');
var $chatPage = $('.chat.page');
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput;
var socket = io();
function addParticipantsMessage(data) {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
function setUsername() {
username = cleanInput($usernameInput.val().trim());
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
socket.emit('add user', username);
}
}
function sendMessage() {
var message = $inputMessage.val();
message = cleanInput(message);
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
socket.emit('new message', message);
}
}
function log(message, options) {
var $el = $(
message.match(/welcome/i) ? '<marquee scrollamount="50">' : '<li>'
).addClass('log').text(message);
addMessageElement($el, options);
$(document).ready(function() {
var url1 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g,
linkThis = function() {
var childNodes = this.childNodes,
i = childNodes.length;
while (i--) {
var n = childNodes[i];
if (n.nodeType == 3) {
var html = $.trim(n.nodeValue);
if (html) {
html = html.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(url1, '$1 $2$3')
.replace(url2, '$1 $2$5');
$(n).after(html).remove();
}
}
else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {
linkThis.call(n);
}
}
};
$.fn.link = function() {
return this.each(linkThis);
};
$('body').link();
});
}
function addChatMessage(data, options) {
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
$(document).ready(function() {
var url1 = /(^|<|\s)(www\..+?\..+?)(\s|>|$)/g,
url2 = /(^|<|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|>|$)/g,
linkThis = function() {
var childNodes = this.childNodes,
i = childNodes.length;
while (i--) {
var n = childNodes[i];
if (n.nodeType == 3) {
var html = $.trim(n.nodeValue);
if (html) {
html = html.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(url1, '$1 $2$3')
.replace(url2, '$1 $2$5');
$(n).after(html).remove();
}
}
else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {
linkThis.call(n);
}
}
};
$.fn.link = function() {
return this.each(linkThis);
};
$('body').link();
});
}
function addChatTyping(data) {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
function removeChatTyping(data) {
getTypingMessages(data).fadeOut(function() {
$(this).remove();
});
}
function addMessageElement(el, options) {
var $el = $(el);
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
function cleanInput(input) {
return $('<div/>').text(input).html();
}
function updateTyping() {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function() {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
function getTypingMessages(data) {
return $('.typing.message').filter(function(i) {
return $(this).data('username') === data.username;
});
}
function getUsernameColor(username) {
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
$window.keydown(function(event) {
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
$loginPage.click(function() {
$currentInput.focus();
});
$inputMessage.click(function() {
$inputMessage.focus();
});
socket.on('login', function(data) {
connected = true;
var message = "";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
socket.on('new message', function(data) {
addChatMessage(data);
});
socket.on('user joined', function(data) {
log(data.username + ' joined');
addParticipantsMessage(data);
});
socket.on('user left', function(data) {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
});
socket.on('typing', function(data) {
addChatTyping(data);
});
socket.on('stop typing', function(data) {
removeChatTyping(data);
});
socket.on('disconnect', function() {
log('you have been disconnected');
});
socket.on('reconnect', function() {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function() {
log('attempt to reconnect has failed');
});
});
i tried this html code:
!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="theme-color" content="#3af">
<meta name="viewport" content="target-densitydpi=device-dpi, initial-scale=1.0, user-scalable=no" />
<meta name="description" content="A fully functioning public chat mobile friendly and supports links change the color to whatever you want even invert it if you want!">
<title>Chat</title>
<link href="icon.png" rel="icon" type="image/x-icon" />
</head>
<body>
<ul class="pages">
<meta name="theme-color" content="#3af">
<li class="chat page">
<div class="chatArea">
<ul class="messages"></ul>
</div>
<input class="inputMessage" placeholder="Type here..."/>
</li>
<li class="login page">
<div class="form">
<h3 class="title" style="font-family: ubuntu">Enter Your Nickname:</h3>
<input class="usernameInput" type="text" maxlength="10"/>
<meta name="theme-color" content="#3af">
</div>
</li>
</ul>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="main.js"></script>
<meta name="theme-color" content="#3af">
</body>
</html>

Related

WebRTC video stream works on some devices but does not work on other devices

I've been working on an app that uses webRTC and it works perfectly on all of MY devices from different networks. However, when other people try to use it from their devices, some can connect and some can't. I collected all the WebRTC chrome internal dumps and attached some of them below.
Local dump link:
https://www.dropbox.com/home?preview=local_dump.txt
Working device(remote) dump link:
https://www.dropbox.com/home?preview=working_device_dump.txt
Not working device(remote) dump link:
https://www.dropbox.com/home?preview=not_working_dump.txt
Javascript is attached below:
I traversed a number of stackoverflow posts and my JS should be up-to-date. I am guessing the codecs are making the stream fail but I don't know what to fix.
// get DOM elements
var dataChannelLog = document.getElementById('data-channel'),
iceConnectionLog = document.getElementById('ice-connection-state'),
iceGatheringLog = document.getElementById('ice-gathering-state'),
signalingLog = document.getElementById('signaling-state');
// peer connection
var pc = null;
// data channel
var dc = null, dcInterval = null;
function createPeerConnection() {
var config = {
sdpSemantics: 'unified-plan'
};
if (document.getElementById('use-stun').checked) {
config.iceServers = [{urls: ['stun:stun.l.google.com:19302']}];
}
var pc = new RTCPeerConnection(config);
// connect audio / video
pc.addEventListener('track', function(evt) {
if (evt.track.kind == 'video')
document.getElementById('video').srcObject = evt.streams[0];
else
document.getElementById('audio').srcObject = evt.streams[0];
});
return pc;
}
function negotiate() {
return pc.createOffer().then(function(offer) {
return pc.setLocalDescription(offer);
}).then(function() {
// wait for ICE gathering to complete
return new Promise(function(resolve) {
if (pc.iceGatheringState === 'complete') {
resolve();
} else {
function checkState() {
if (pc.iceGatheringState === 'complete') {
pc.removeEventListener('icegatheringstatechange', checkState);
resolve();
}
}
pc.addEventListener('icegatheringstatechange', checkState);
}
});
}).then(function() {
var offer = pc.localDescription;
var codec;
codec = document.getElementById('audio-codec').value;
// if (codec !== 'default') {
// offer.sdp = sdpFilterCodec('audio', codec, offer.sdp);
// }
//
// codec = document.getElementById('video-codec').value;
// if (codec !== 'default') {
// offer.sdp = sdpFilterCodec('video', codec, offer.sdp);
// }
document.getElementById('offer-sdp').textContent = offer.sdp;
console.log(offer);
return fetch('/offer', {
body: JSON.stringify({
sdp: offer.sdp,
type: offer.type,
video_transform: document.getElementById('video-transform').value
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
}).then(function(response) {
return response.json();
}).then(function(answer) {
document.getElementById('answer-sdp').textContent = answer.sdp;
return pc.setRemoteDescription(answer);
}).catch(function(e) {
/*
TODO: Presentation and logic mix a lot here (naturally). I don't think we need a framework (even though the
JS world has ALL OF THEM), but maybe we can group all presentation related things in separate functions,
for example change this to be catch(showConnectionError) and put the DOM logic inside
function showConnectionError(e) {...}?
*/
var el = document.querySelector('video');
var newEl = document.createElement('img');
newEl.src = '/working.png';
newEl.style.height = '100%'
el.parentNode.replaceChild(newEl, el);
});
}
function start() {
document.getElementById('start').style.display = 'none';
pc = createPeerConnection();
var time_start = null;
function current_stamp() {
if (time_start === null) {
time_start = new Date().getTime();
return 0;
} else {
return new Date().getTime() - time_start;
}
}
if (document.getElementById('use-datachannel').checked) {
var parameters = JSON.parse(document.getElementById('datachannel-parameters').value);
dc = pc.createDataChannel('chat', parameters);
dc.onclose = function() {
clearInterval(dcInterval);
dataChannelLog.textContent += '- close\n';
};
dc.onopen = function() {
dataChannelLog.textContent += '- open\n';
dcInterval = setInterval(function() {
var message = 'ping ' + current_stamp();
dataChannelLog.textContent += '> ' + message + '\n';
dc.send(message);
}, 1000);
};
dc.onmessage = function(evt) {
dataChannelLog.textContent += '< ' + evt.data + '\n';
if (evt.data.substring(0, 4) === 'pong') {
var elapsed_ms = current_stamp() - parseInt(evt.data.substring(5), 10);
dataChannelLog.textContent += ' RTT ' + elapsed_ms + ' ms\n';
}
};
}
var constraints = {
audio: document.getElementById('use-audio').checked,
video: false
};
if (document.getElementById('use-video').checked) {
var resolution = document.getElementById('video-resolution').value;
if (resolution) {
resolution = resolution.split('x');
constraints.video = {
width: parseInt(resolution[0], 0),
height: parseInt(resolution[1], 0)
};
} else {
constraints.video = true;
}
}
if (constraints.audio || constraints.video) {
if (constraints.video) {
document.getElementById('media').style.display = 'block';
}
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
stream.getTracks().forEach(function(track) {
pc.addTrack(track, stream);
});
return negotiate();
/*
TODO: Can this also be promise-based? -> .catch(function(err) { ... })
*/
}, function(err) {
alert('Could not acquire media: ' + err);
});
} else {
negotiate();
}
document.getElementById('stop').style.display = 'inline-block';
}
function stop() {
document.getElementById('stop').style.display = 'none';
// close data channel
if (dc) {
dc.close();
}
// close transceivers
if (pc.getTransceivers) {
pc.getTransceivers().forEach(function(transceiver) {
if (transceiver.stop) {
transceiver.stop();
}
});
}
// close local audio / video
pc.getSenders().forEach(function(sender) {
sender.track.stop();
});
// close peer connection
setTimeout(function() {
pc.close();
}, 500);
}
function sdpFilterCodec(kind, codec, realSdp) {
var allowed = []
var rtxRegex = new RegExp('a=fmtp:(\\d+) apt=(\\d+)\r$');
var codecRegex = new RegExp('a=rtpmap:([0-9]+) ' + escapeRegExp(codec))
var videoRegex = new RegExp('(m=' + kind + ' .*?)( ([0-9]+))*\\s*$')
var lines = realSdp.split('\n');
var isKind = false;
for (var i = 0; i < lines.length; i++) {
if (lines[i].startsWith('m=' + kind + ' ')) {
isKind = true;
} else if (lines[i].startsWith('m=')) {
isKind = false;
}
if (isKind) {
var match = lines[i].match(codecRegex);
if (match) {
allowed.push(parseInt(match[1]));
}
match = lines[i].match(rtxRegex);
if (match && allowed.includes(parseInt(match[2]))) {
allowed.push(parseInt(match[1]));
}
}
}
var skipRegex = 'a=(fmtp|rtcp-fb|rtpmap):([0-9]+)';
var sdp = '';
isKind = false;
for (var i = 0; i < lines.length; i++) {
if (lines[i].startsWith('m=' + kind + ' ')) {
isKind = true;
} else if (lines[i].startsWith('m=')) {
isKind = false;
}
if (isKind) {
var skipMatch = lines[i].match(skipRegex);
if (skipMatch && !allowed.includes(parseInt(skipMatch[2]))) {
continue;
} else if (lines[i].match(videoRegex)) {
sdp += lines[i].replace(videoRegex, '$1 ' + allowed.join(' ')) + '\n';
} else {
sdp += lines[i] + '\n';
}
} else {
sdp += lines[i] + '\n';
}
}
return sdp;
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Using PhantomJS for screenshots after logging in

I am attempting to use PhantomJs to crawl our ASP.Net web app and take screenshots of a list of pages defined in a simple text file of URLs. I have been able to get it working fine for pages not behind the log-in wall, but can't seem to get my PhantomJs instance to get authenticated. Log messages show that I'm doing things in the right order with my two interval functions - any ideas how to make sure I'm logged in first?
var fs = require('fs'),
system = require('system');
var content = '',
f = null,
lines = null,
pages =null,
destinations = null,
eol = system.os.name == 'windows' ? "\r\n" : "\n";
//read in a line break separated list of urls
//page at index 0 is the login page
try {
f = fs.open(".\\urls.txt", "r");
content = f.read();
} catch (e) {
console.log(e);
}
if (f) {
f.close();
}
if (content) {
lines = content.split(eol);
pages = new Array();
destinations = new Array();
for (var i = 0, len = lines.length; i < len; i++) {
var pageName = lines[i].substring(lines[i].lastIndexOf('/') + 1);
pages[i] = pageName;
destinations[i] = ".\\NewScreenShot\\" + pageName + '.png';
}
}
console.log('Pages found: ' + pages.length);
var page = require('webpage').create();
var loginIndex = 0;
var loginInProgress = false;
var loginSteps = [
function() {
//Enter Credentials
page.evaluate(function() {
document.getElementById("txtusername").value = "ausername#mysite.com";
document.getElementById("txtpassword").value ="12345678";
return;
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementById("form1");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
}
];
var LoadPage = function() {
if (!loadInProgress && pageindex < pages.length) {
console.log("image " + (pageindex + 1) + " of " + lines.length);
page.open(lines[pageindex]);
}
if (pageindex == lines.length) {
console.log("<< Image render complete! >>");
phantom.exit();
}
}
//PNG RENDER
var pageindex = 0;
var loadInProgress = false;
var interval = setInterval(LoadPage, 500);
page.onLoadStarted = function() {
loadInProgress = true;
if(pageindex == 0) {
loginInProgress = true;
}
console.log('page ' + (pageindex + 1) + ' load started');
};
page.onLoadFinished = function() {
loadInProgress = false;
if(pageindex == 0)
{
loginInProgress = false;
console.log("stopping page interval");
clearInterval(interval);
}
page.evaluate(
function () {
var scaleVal = "scale("+arguments[0] || '1.0'+")";
document.body.style.webkitTransform = scaleVal;
}
);
console.log("rendering:" + destinations[pageindex]);
page.render(destinations[pageindex]); // RENDER PAGE //
if (pageindex == 0){
var loginInterval = setInterval(function() {
if (!loginInProgress && typeof loginSteps[loginIndex] == "function") {
console.log("login step: " + loginIndex )
loginSteps[loginIndex]();
loginIndex++;
}
if (typeof loginSteps[loginIndex] != "function") {
console.log("stopping login interval");
clearInterval(loginInterval);
console.log("starting page interval");
setInterval(LoadPage, 500);
}
}, 50);
}
pageindex++;
}
Turns out the problem was form submit vs button click. working code below:
var urlsLocation = "C:\\PhantomJs\\urls.txt";
var newScreenshotFolder = "C:\\PhantomJs\\NewScreenShot\\";
var fs = require('fs'),
system = require('system');
var content = '',
f = null,
lines = null,
pages =null,
destinations = null,
eol = system.os.name == 'windows' ? "\r\n" : "\n";
//read in a return separated list of urls
try {
f = fs.open(urlsLocation, "r");
content = f.read();
} catch (e) {
console.log(e);
}
if (f) {
f.close();
}
if (content) {
lines = content.split(eol);
pages = new Array();
destinations = new Array();
for (var i = 0, len = lines.length; i < len; i++) {
var pageName = lines[i].substring(lines[i].lastIndexOf('/') + 1);
pages[i] = pageName;
destinations[i] = newScreenshotFolder + pageName.replace(/[^a-zA-Z0-9\.]/g, "") + '.png';
}
}
console.log('Pages found: ' + pages.length);
var page = require('webpage').create();
var loginIndex = 0;
var loginInProgress = false;
var loginCompleted = false;
var loginSteps = [
function() {
//Enter Credentials
page.evaluate(function() {
document.getElementById("txtusername").value = "testemail#gmail.com";
document.getElementById("txtpassword").value = "12345678";
return;
});
},
function() {
//Login
page.evaluate(function() {
document.getElementById("btnLogin").click();
return;
});
}
];
var LoadPage = function() {
if (!loadInProgress && pageindex < pages.length) {
console.log("image " + (pageindex + 1) + " of " + lines.length);
page.open(lines[pageindex]);
}
if (pageindex == lines.length) {
console.log("<< Image render complete! >>");
phantom.exit();
}
}
//PNG RENDER
var pageindex = 0;
var loadInProgress = false;
var interval = setInterval(LoadPage, 500);
page.onLoadStarted = function() {
loadInProgress = true;
if(pageindex == 0) {
loginInProgress = true;
}
console.log('page ' + (pageindex + 1) + ' load started');
};
page.onLoadFinished = function() {
loadInProgress = false;
if(pageindex == 0)
{
loginInProgress = false;
console.log("stopping page interval");
clearInterval(interval);
}
page.evaluate(
function () {
var scaleVal = "scale("+arguments[0] || '1.0'+")";
document.body.style.webkitTransform = scaleVal;
}
);
console.log("rendering:" + destinations[pageindex]);
page.render(destinations[pageindex]); // RENDER PAGE //
if (pageindex == 0){
var loginInterval = setInterval(function() {
if (!loginInProgress && typeof loginSteps[loginIndex] == "function") {
console.log("login step: " + loginIndex )
loginSteps[loginIndex]();
loginIndex++;
}
if (typeof loginSteps[loginIndex] != "function") {
console.log("stopping login interval");
clearInterval(loginInterval);
console.log("starting page interval");
setInterval(LoadPage, 1000);
}
}, 50);
}
pageindex++;
}

use multiple triggers in jQuery autocomplete using mutiple datasets

I am trying to implement twitter/facebook like auto-complete on a textarea. Now Till now i have implemented it for single trigger "#". But I want it to work for 2 triggers "#" and "#".
Both will have different data sets.
Here is for the single dataset. This one works perfectly.
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<textarea class="searchBox" cols="20" rows="10"></textarea>
</body>
</html>
JS
var triggered = false; // By default trigger is off
var trigger = "#"; // Defining the trigger
var data = [
{
label: "abc",
value: "abc#live.com"
},
{
label: "def",
value: "deg#altman.com"
},
{
label: "ghf",
value: "sds#lane.com"
}
];
$(".searchBox").autocomplete({
minLength: 0,
source: data,
search: function () {
if (!triggered) {
return false;
}
},
select: function (event, ui){
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos) + ui.item.value;
triggered = false;
return false;
},
focus: function () {
return false;
}
}).data( "ui-autocomplete" )._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + "<b>" + item.label + "</b> " + item.value + "</a>")
.appendTo(ul);
};
$('.searchBox').keyup(function (e) {
if (e.keyCode == 38 || e.keyCode == 40) {
return;
}
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search",query);
} else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});
here is the fiddle : http://jsbin.com/qakefini/7/edit
Now what i tried for 2 triggers :
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<textarea class="searchBox" cols="20" rows="10"></textarea>
</body>
</html>
JS
var triggered = false;
var trigger1 = "#";
var trigger2 = "#"; // Defining the trigger
var trigger = "#";
var data1 = [
{
label: "abc",
value: "abc#live.com"
},
{
label: "def",
value: "deg#altman.com"
},
{
label: "ghf",
value: "sds#lane.com"
}
];
var data2 = [
{
tag: "what"
},
{
tag: "hello"
},
{
tag: "there"
}
];
var data = jQuery.extend(true, {}, data1);
$(".searchBox").autocomplete({
minLength: 0,
source: data,
search: function () {
if (!triggered) {
return false;
}
},
select: function (event, ui){
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos) + ui.item.value;
triggered = false;
return false;
},
focus: function () {
return false;
}
}).data( "ui-autocomplete" )._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + "<b>" + item.label + "</b>" + item.value + "</a>")
.appendTo(ul);
};
$(".searchBox").keypress(function (e) {
if (e.charCode != 64 && e.charCode != 35) {
return;
}
if (e.charCode == 64) {
trigger = trigger1;
data = jQuery.extend(true, {}, data1);
}
else if (e.charCode == 35 ){
trigger = trigger2;
data = jQuery.extend(true, {}, data2);
}
});
$(".searchBox").autocomplete({
minLength: 0,
source: data,
search: function () {
if (!triggered) {
return false;
}
},
select: function (event, ui){
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos) + ui.item.value;
triggered = false;
return false;
},
focus: function () {
return false;
}
}).data( "ui-autocomplete" )._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + "<b>" + item.label + "</b> " + item.value + "</a>")
.appendTo(ul);
};
$('.searchBox').keyup(function (e) {
if (e.keyCode == 38 || e.keyCode == 40) {
return;
}
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search",query);
} else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});
And here is the fiddle: http://jsbin.com/qakefini/22/edit
It is not responding to the search queries. Where it is going wrong ?
Please help.
Thanks.
regards.
In your second example, you have two arrays data1 and data2, yet you're telling the .autocomplete() that the data source is data (the line reads: source: data) - which is undefined.

JQuery: How to refactor JQuery interaction with interface?

The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )

S3Slider jQuery Stop After One Rotation

I'm using an S3Slider on WordPress. I'd like it to stop after one rotation, but can't seem to figure out the setting.
The following code is used in the slider.js file. Right now it's live at http://beaconwc.com on the frontpage, would like it to show the two slides and then stop until the user refreshes the page.
(function($){
$.fn.s3Slider = function(vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var capOpacity = vars.captionOpacity || .7;
var items = $("#" + element[0].id + "Content ." + element[0].id + "Image");
var itemsSpan = $("#" + element[0].id + "Content ." + element[0].id + "Image div");
itemsSpan.css({
'opacity': capOpacity,
'display': 'none'
});
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true) {
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};
})(jQuery);
Thanks!
Source
http://www.serie3.info/s3slider/

Categories

Resources