JW Player - Amazon Web Services CDN and Advanced Javascript Debugging - javascript

I have a customized JW Player 7 Pro embedded on the following page: http://dev.sharepoint-videos.com/jw-player-self-hosted/.
The embed code is as follows:
<!--Course Video, Scripts and Style-->
<div id="visualSPPlayer">Loading the player...</div>
<script type="text/javascript">
var playerInstance = jwplayer("visualSPPlayer");
playerInstance.setup({
file: "http://dbt8c2ssdzlxg.cloudfront.net/Search2013.mp4",
primary: "HTML5",
image: "https://assets-jpcust.jwpsrv.com/thumbs/2kOAeo0k-320.jpg?1443200073230",
width: "100%",
aspectratio: "16:9",
tracks: [
{
file: "http://dbt8c2ssdzlxg.cloudfront.net/captions/Search/Captions.srt",
label: "English",
kind: "captions",
},
{
file: 'http://dbt8c2ssdzlxg.cloudfront.net/chapters/Search/Chapters.vtt',
kind: 'chapters'
},
{
file: "http://dbt8c2ssdzlxg.cloudfront.net/thumbnails/search_thumbnails.vtt",
kind: "thumbnails"
}
],
skin: {
name: "vapor",
active: "#E16933",
inactive: "#E16933",
background: "#333333"
}
});
</script>
<script type="application/javascript" src="http://dev.sharepoint-videos.com/wp-content/themes/symplex-child/js/player.js"></script>
<link rel="stylesheet" href="http://dev.sharepoint-videos.com/wp-content/themes/symplex-child/css/player.css" type="text/css" media="screen"/>
The player.js file contents:
jQuery(document).ready(function () {
jQuery(function ($) {
var playerInstance = jwplayer();
var chapters = [];
var captions = [];
var toc = [];
var caption = -1;
var matches = [];
var seekArr = [];
var seekPos = [];
var seePos;
var query = "";
var cycle = -1;
var transcript = document.getElementById('courseTranscript');
var search = document.getElementById('courseSearch');
var match = document.getElementById('courseMatch');
var caption_file;
var chapter_file;
playerInstance.onReady(function () {
//Self-Hosted
caption_file = playerInstance.getPlaylist()[0].tracks[0].file;
chapter_file = playerInstance.getPlaylist()[0].tracks[1].file;
if (playerInstance.getRenderingMode() == "flash") {
return;
}
tag = document.querySelector('video');
tag.defaultPlaybackRate = 1.0;
tag.playbackRate = 1.0;
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/hare.png", "1.5x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 1.5;
}, "playerHighSpeed");
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/normal.png", "1.0x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 1.0;
}, "playerNormalSpeed");
playerInstance.addButton("http://dev.sharepoint-videos.com/wp-content/uploads/2015/09/snail.png", "0.5x", function () {
playerInstance.seek(playerInstance.getPosition());
tag.playbackRate = 0.5;
}, "playerSlowSpeed");
});
//Adds Player Focus on Playing
playerInstance.on('play', function () {
$('html, body').animate({
scrollTop: $(".jwplayer").offset().top - 190
}, 1000);
});
playerInstance.onReady(function () {
$.get(caption_file, function (data) {
data = data.trim();
var t = data.split("\n\r\n");
for (var i = 0; i < t.length; i++) {
var c = parse(t[i]);
chapters.push(c);
}
loadCaptions();
loadChapters();
});
//
});
// Load chapters / captions
function loadCaptions() {
$.get(caption_file, function (data) {
data = data.trim();
var t = data.split("\n\r\n");
t.pop();
var h = "<p>";
var s = 0;
for (var i = 0; i < t.length; i++) {
var c = parse(t[i]);
if (s < chapters.length && c.begin > chapters[s].begin) {
s++;
}
h += "<span id='caption" + i + "'>" + c.text + "</span>";
captions.push(c);
}
transcript.innerHTML = h + "</p>";
});
};
function parse(d) {
var a = d.split("\n");
//console.log(a[1]);
var i = a[1].indexOf(' --> ');
var t = a[2]; //Caption text
if (a[3]) {
t += " " + a[3];
}
t = t.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return {
begin: seconds(a[1].substr(0, i)),
btext: a[1].substr(3, i - 7),
end: seconds(a[1].substr(i + 5)),
text: t
}
};
function seconds(s) {
var a = s.split(':');
secs = a[2].substring(0, a[2].indexOf(','));
var r = Number(secs) + Number(a[a.length - 2]) * 60;
if (a.length > 2) {
r += Number(a[a.length - 3]) * 3600;
}
return r;
};
function toc_seconds(s) {
var a = s.split(':');
secs = a[2].substring(0, a[2].indexOf('.'));
var r = Number(secs) + Number(a[a.length - 2]) * 60;
if (a.length > 2) {
r += Number(a[a.length - 3]) * 3600;
}
return r;
};
function toc_time(s) {
var a = s.split(':');
var ms = a[2].split(".");
var h = a[0];
if (h != "00") {
var r = a[0] + ":" + a[1] + ":" + ms[0];
} else {
var r = a[1] + ":" + ms[0];
}
return r;
};
// Highlight current caption and chapter
playerInstance.onTime(function (e) {
var p = e.position;
for (var j = 0; j < captions.length; j++) {
if (captions[j].begin < p && captions[j].end > p) {
if (j != caption) {
var c = document.getElementById('caption' + j);
if (caption > -1) {
document.getElementById('caption' + caption).className = "";
}
c.className = "current";
if (query == "") {
transcript.scrollTop = c.offsetTop - transcript.offsetTop - 40;
}
caption = j;
}
break;
}
}
});
// Hook up interactivity
transcript.addEventListener("click", function (e) {
if (e.target.id.indexOf("caption") == 0) {
var i = Number(e.target.id.replace("caption", ""));
playerInstance.seek(captions[i].begin);
}
});
/**/
search.addEventListener('focus', function (e) {
setTimeout(function () {
search.select();
}, 100);
resetSearch();
$("#prevMatchLink").hide();
$("#nextMatchLink").hide();
});
search.addEventListener('keydown', function (e) {
if (e.keyCode == 27) {
resetSearch();
$("#prevMatchLink").hide();
$("#nextMatchLink").hide();
} else if (e.keyCode == 13) {
$("#prevMatchLink").show();
$("#nextMatchLink").show();
var q = this.value.toLowerCase();
if (q.length > 0) {
if (q == query) {
if (cycle >= matches.length - 1) {
cycleSearch(0);
} else {
cycleSearch(cycle + 1);
}
} else {
resetSearch();
searchTranscript(q);
}
} else {
resetSearch();
}
} else if (e.keyCode == 37) {
cycleSearch(cycle - 1);
}
else if (e.keyCode == 39) {
cycleSearch(cycle + 1);
}
});
$("#prevMatchLink").click(function (e) {
e.preventDefault();
cycleSearch(cycle - 1);
});
$("#nextMatchLink").click(function (e) {
e.preventDefault();
cycleSearch(cycle + 1);
});
// Execute search
function searchTranscript(q) {
matches = [];
query = q;
for (var i = 0; i < captions.length; i++) {
var m = captions[i].text.toLowerCase().indexOf(q);
if (m > -1) {
document.getElementById('caption' + i).innerHTML =
captions[i].text.substr(0, m) + "<em>" +
captions[i].text.substr(m, q.length) + "</em>" +
captions[i].text.substr(m + q.length);
matches.push(i);
}
}
if (matches.length) {
cycleSearch(0);
} else {
resetSearch();
}
};
function cycleSearch(i) {
if (cycle > -1) {
var o = document.getElementById('caption' + matches[cycle]);
o.getElementsByTagName("em")[0].className = "";
}
var c = document.getElementById('caption' + matches[i]);
c.getElementsByTagName("em")[0].className = "current";
match.innerHTML = (i + 1) + " of " + matches.length;
transcript.scrollTop = c.offsetTop - transcript.offsetTop - 40;
cycle = i;
};
function resetSearch() {
if (matches.length) {
for (var i = 0; i < captions.length; i++) {
document.getElementById('caption' + i).innerHTML = captions[i].text;
}
}
query = "";
matches = [];
match.innerHTML = "0 of 0";
cycle = -1;
transcript.scrollTop = 0;
};
var videoTitle = $(".videoTitle").text();
var hasPlayed = false;
playerInstance.onBeforePlay(function (event) {
if (hasPlayed == false) {
ga('send', 'event', 'Video', 'Play', videoTitle);
hasPlayed = true;
}
});
//Can be used to trigger the Course to Marked Completed so the user doesn't have to
playerInstance.on('complete', function () {
});
function loadChapters() {
$.get(chapter_file, function (data) {
data = data.trim();
var c = data.split("\n\r\n");
var d;
for (var i = 0; i < c.length; i++) {
d = c[i].split("\n");
//pushes in Title for each chapter
toc.push(d[0]);
//pushes in the time intervals for each chapter
seekArr.push(d[1]);
};
for (var a = 0; a < seekArr.length; a++) {
//Splits the time interval and pushes the start interval for each chapter
var tempPos = seekArr[a].split(" --> ");
seekPos.push(tempPos[0]);
};
runTOC(seekPos);
var toc_output = "";
$.each(toc, function (i, v) {
toc_output += "<li class=ch" + i + "><a href='#' onclick='jwplayer().seek(" + toc_seconds(seekPos[i]) + ");'>" + v + "</a> (" + toc_time(seekPos[i]) + ")</li>"
});
if (toc.length < 7) {
toc_output += " <li class='blank'> </li><li class='blank'> </li>";
}
$(".courseTitles ul").html(toc_output);
});
};
function runTOC(x) {
playerInstance.onTime(function (event) {
for (var i = 0; i < x.length; i++) {
if (event.position > toc_seconds(x[i])) {
$(".courseTitles ul li").removeClass("active");
$(".courseTitles ul li.ch" + i).addClass('active');
}
};
});
}
});
});
We are hosting the video and Chapter/Captions VTT files using Amazon Web Services with Cloudfront.
We have included the interactive transcript from the captions as well as dynamic video chapters to be loaded once the video is ready to be played.
One thing I have noticed is that the chapters and the transcript do not always load and require the page to be refreshed several times so I was thinking that maybe it was a caching issue on the AWS side of the equation.
I have used Google Chrome and there are no errors in the developers console when the chapters and transcript do not load.
It should be noted that this functionality was working flawlessly when were using the JW Platform cloud hosted solution so it seems to be a factor of the AWS/Cloudfront CDN.
function load_jwp_scripts() {
wp_enqueue_script('jwplayer-js', plugins_url( "/js/jwplayer.js", __FILE__), array(), '1.0', false);
wp_enqueue_script('jwplayer-license-js', plugins_url( "/js/jwplayer_license.js", __FILE__), array(), '1.0', false);
wp_enqueue_script('jwplayer-player-js', plugins_url( "/js/player.js", __FILE__), array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'load_jwp_scripts');

I was able to find a workable solution to my problem.
The issue was the use of the $(document).ready declaration. It is not compatible with jwplayer.on("ready").
Removing that and it is rendering properly again.

Related

How to make timer not to restart after page refresh in psgTimer library of Jquery?

This is the code snippet of psgTimer Jquery Library, I want not to reload the timer when the page refreshes. I try to save the time diff in local storage. But not able to get the result. Please provide the solution.
(function () {
var callbacks = {
onInit: function () {
},
onStart: function () {
},
onStop: function () {
},
onEnd: function () {
},
onChangeStart: function () {
},
onChangeEnd: function () {
}
};
var base = {
stopped: true,
timezone: 0,
diff: null,
isEnd: false
};
var PsgTimer = function (selector, options) {
var timer = this;
if (selector.nodeType === Node.ELEMENT_NODE) {
timer.container = $(selector);
} else if (typeof selector === 'string') {
timer.selector = selector;
timer.container = $(timer.selector);
} else if (typeof selector === 'object') {
options = selector;
timer.selector = options.selector;
timer.container = $(timer.selector);
}
timer.options = $.extend({}, {
selector: '#psgTimer',
animation: false,
multipleBlocks: false,
endDateTime: undefined,
// currentDateTime: window.serverTime['U'] * 1000 || Date.now(),
currentDateTime: Date.now(),
labels: {
days: timer.container.attr('data-label-days') ? timer.container.attr('data-label-days') : false,
hours: timer.container.attr('data-label-hours') ? timer.container.attr('data-label-hours') : false,
minutes: timer.container.attr('data-label-minutes') ? timer.container.attr('data-label-minutes') : false,
seconds: timer.container.attr('data-label-seconds') ? timer.container.attr('data-label-seconds') : false
}
}, options);
timer.callbacks = timer.options.callbacks = $.extend({}, callbacks, timer.options.callbacks);
timer.base = $.extend({}, base);
if (typeof timer.options.endDateTime === 'string') {
timer.options.endDateTime = setTimerEndFromString(timer, timer.options.endDateTime);
}
timer.container.length ? timer.init() : console.log('No timer element on this page');
};
PsgTimer.prototype.init = function () {
var timer = this,
options = this.options;
var timerEnd = timer.container.attr('data-timer-end');
if (timerEnd !== undefined) {
options.endDateTime = setTimerEndFromString(timer, timerEnd);
}
// options.endDateTime = options.endDateTime + (timer.base.timezone * 1000 * 60 * 60);
timer.countdown = transformCountToArray(getCurrentCountDown(timer), options.multilpeBlocks);
timer.container.addClass('psgTimer').append(createMarkup(timer));
if (options.animation) {
timer.container.addClass('psgTimer_' + options.animation);
}
timer.query = setQueries(timer);
timer.callbacks.onInit();
if (!timer.base.isEnd) {
timer.start();
}
};
PsgTimer.prototype.start = function () {
var timer = this;
if (timer.base.stopped) {
timer.base.stopped = false;
timer.intervalId = setInterval(function () {
updateCounter(timer);
}, 1000);
timer.callbacks.onStart();
}
};
PsgTimer.prototype.restart = function () {
var timer = this;
timer.options.currentDateTime = Date.now();
timer.start();
};
PsgTimer.prototype.stop = function () {
var timer = this;
timer.base.stopped = true;
clearTimeout(timer.intervalId);
timer.callbacks.onStop();
};
var getCurrentCountDown = function (timer) {
var options = timer.options;
var base = timer.base;
options.currentDateTime = options.currentDateTime + 1001;
base.diff = options.endDateTime - options.currentDateTime;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
if (base.diff > 0) {
var total = parseFloat(((((base.diff / 1000.0) / 60.0) / 60.0) / 24.0));
days = parseInt(total);
total -= days;
total *= 24.0;
hours = parseInt(total);
total -= hours;
total *= 60.0;
minutes = parseInt(total);
total -= minutes;
total *= 60;
seconds = parseInt(total);
} else {
timer.callbacks.onEnd();
timer.stop();
timer.base.isEnd = true;
}
return {
days: {
amount: days,
max: Infinity,
className: 'days'
},
hours: {
amount: hours,
max: 24,
className: 'hours'
},
minutes: {
amount: minutes,
max: 60,
className: 'minutes'
},
seconds: {
amount: seconds,
max: 60,
className: 'seconds'
}
}
};
var transformCountToArray = function (count, multilpeBlocks) {
if (typeof count === 'object') {
for (var unit in count) {
if (count.hasOwnProperty(unit)) {
count[unit].amount = count[unit].amount.toString();
if (count[unit].amount.length < 2) {
count[unit].amount = '0' + count[unit].amount;
}
if (multilpeBlocks) {
count[unit].amount = count[unit].amount.split('');
} else {
count[unit].amount = [count[unit].amount];
}
}
}
}
return count;
};
var getTimeZone = function (string) {
var hours, minutes;
var number = string.replace(/\D/g, '');
var digit = string.replace(/[^+-]/g, '');
var multiplier = digit === '-' ? (-1) : 1;
if (number.length >= 3) {
hours = Number(number.substr(0, number.length - 2));
minutes = Number(number.substr(number.length - 2, 2));
} else {
hours = Number(number);
minutes = 0;
}
return (hours + minutes/60) * multiplier;
};
var setTimerEndFromString = function (timer, endTimeString) {
var timerDate = {};
var timerEnd = endTimeString.split(' ');
var endTime;
var timeExp = /^([0-1]\d|2[0-3])(:[0-5]\d){1,2}$/;
var dateExp = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
var zoneExp = /(UTC|GMT)[+-](\d{1,2}([:,.]?\d{2})?)/;
for (var i = 0; i < timerEnd.length; i++) {
if (timerEnd[i].match(timeExp)) {
timerDate.time = timerEnd[i].split(':');
} else if (timerEnd[i].match(dateExp)) {
timerDate.date = timerEnd[i].split('.');
} else if (timerEnd[i].match(zoneExp)) {
timer.base.timezone = getTimeZone(timerEnd[i]);
} else {
console.log('Wrong end time.');
}
}
timerDate.year = parseInt(timerDate.date[2]) || 0;
timerDate.month = parseInt(timerDate.date[1]) - 1 || 0;
timerDate.day = parseInt(timerDate.date[0]) || 0;
timerDate.hours = parseInt(timerDate.time[0]) || 0;
timerDate.minutes = parseInt(timerDate.time[1]) || 0;
timerDate.seconds = parseInt(timerDate.time[2]) || 0;
timerDate.miliseconds = parseInt(timerDate.time[3]) || 0;
endTime = Date.UTC(timerDate.year, timerDate.month, timerDate.day, timerDate.hours, timerDate.minutes, timerDate.seconds, timerDate.miliseconds);
return endTime;
};
var createMarkup = function (timer) {
var countdown = timer.countdown;
var markup = {};
for (var unit in countdown) {
if (countdown.hasOwnProperty(unit)) {
var numberBlocks = '';
countdown[unit].amount.forEach(function (num) {
numberBlocks += numberContainer(timer, num);
});
markup.unit += '<div class="' + countdown[unit].className + ' psgTimer_unit">' + numberBlocks + '</div>';
}
}
markup.numbers = '<div class="psgTimer_numbers">' + markup.unit + '</div>';
markup.full = markup.numbers;
if (
timer.options.labels &&
timer.options.labels.days &&
timer.options.labels.hours &&
timer.options.labels.minutes &&
timer.options.labels.seconds
) {
var labels = timer.options.labels;
markup.labels = '<div class="psgTimer_labels">' +
'<div class="days">' + labels.days + '</div>' +
'<div class="hours">' + labels.hours + '</div>' +
'<div class="minutes">' + labels.minutes + '</div>' +
'<div class="seconds">' + labels.seconds + '</div>' +
'</div>';
markup.full = markup.numbers + markup.labels;
} else {
markup.full = markup.numbers;
}
return markup.full;
};
var numberContainer = function (timer, num) {
var markup = '',
data = 'data-number="' + num + '"';
var numberBlock = '<div class="number" ' + data + '>' + num + '</div>';
if (timer.options.animation === 'fade') {
markup = '<div>' + numberBlock + '</div>';
} else {
markup = numberBlock;
}
return markup;
};
var setQueries = function (timer) {
var countdown = timer.countdown,
query = {};
for (var unit in countdown) {
if (countdown.hasOwnProperty(unit)) {
query[unit] = timer.container.find(numberSelector(timer, countdown[unit].className));
}
}
return query;
};
var numberSelector = function (timer, className) {
var selector = '';
if (timer.options.animation === 'fade') {
selector = '.' + className + ' .number';
} else {
selector = '.' + className + ' .number';
}
return selector;
};
var updateCounter = function (timer) {
timer.callbacks.onChangeStart();
timer.countdown = transformCountToArray(getCurrentCountDown(timer), timer.options.multilpeBlocks);
for (var unit in timer.countdown) {
if (timer.countdown.hasOwnProperty(unit)) {
timer.countdown[unit].amount.forEach(function (number, index) {
if (timer.query[unit][index].getAttribute('data-number') !== number) {
aminate(timer.query[unit][index], number, timer.options.animation);
}
});
}
}
timer.callbacks.onChangeEnd();
};
var aminate = function (el, value, animationType) {
var $el = $(el);
$el.attr('data-number', value);
if (animationType === 'fade') {
animation.fade($el, value);
} else {
$el.html(value);
}
};
var animation = {
fade: function ($el, value) {
var animDuration = 350;
$el.css({
'transition': 'opacity ' + animDuration + 'ms',
'opacity': '0'
});
setTimeout(function () {
$el.html(value).css('opacity', 1);
}, animDuration + 10);
}
};
window.PsgTimer = PsgTimer;
})();
.psgTimer{display:table;margin:0 auto 30px auto;font-size:0;font-family:'Roboto', sans-serif}.psgTimer_numbers>div,.psgTimer_labels>div{display:inline-block;font-size:0;width:124px;text-align:center}.psgTimer_numbers>div{position:relative}.psgTimer_numbers>div:after{content:":";line-height:60px;height:60px;display:block;font-weight:bold;font-size:24px;color:#21272C;position:absolute;top:0;right:-4px}.psgTimer_numbers>div:last-child:after{content:none}.psgTimer_numbers>div>div{display:inline-block;vertical-align:top;width:44px;height:60px;line-height:60px;background:#21272C;box-shadow:0px 4px 8px rgba(0,0,0,0.2);border-radius:6px;font-weight:bold;font-size:24px;text-align:center;color:#FFD631}.psgTimer_numbers>div>div:first-child{margin-right:5px}.psgTimer_labels>div{padding-top:5px !important;font-size:12px;line-height:18px;text-transform:uppercase;letter-spacing:1.2px;color:#21272C}#media screen and (max-width: 640px){.psgTimer_numbers>div,.psgTimer_labels>div{width:74px}.psgTimer_numbers>div{position:relative}.psgTimer_numbers>div:after{line-height:40px;height:40px;font-size:16px;right:-2px}.psgTimer_numbers>div div{width:26px;height:40px;line-height:40px;font-size:16px}.psgTimer_numbers>div div:first-child{margin-right:2px}.psgTimer_labels>div{font-size:10px;line-height:16px}}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<div id="firstTimer"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var timer = new PsgTimer({
selector: '#firstTimer',
currentDateTime: Date.UTC(2018, 0, 26, 12, 0, 0),
endDateTime: Date.UTC(2018, 0, 26, 12, 5, 0),
multilpeBlocks: true,
animation: 'fade',
labels: {
days: 'Days',
hours: 'Hours',
minutes: 'minutes',
seconds: 'seconds'
},
callbacks: {
onInit: function () {
console.log('Hello world!');
}
}
});
})
</script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
</body>
</html>
You can take the reference from psgTimer library
https://www.jqueryscript.net/time-clock/psg-countdown-timer.html

Image slideshow timer speed getting increased when we click on next or previous buttons, using JavaScript

I have written simple image slider using JavaScript. In that I have set 5000 ms timer to slide automatically. but it is getting increased when we click on next or previous button. I have pasted the code below
HTML Code:
<section id="intro">
<div id="prev"><br/><br/><br/><br/><img onclick="rotateImages(0);" src="./images/slider/prev1.png"/></div>
<div id="next"><img onclick="rotateImages(1);" src="./images/slider/next1.png"/></div>
</section>
JavaScript Code:
<script type="text/javascript">
var num = 0;
var temp = 0;
var speed = 5000;
var preloads = [];
preload(
'1.png',
'2.jpg',
'3.jpg',
'4.jpg',
'5.png'
);
function preload() {
for (var c = 0; c < arguments.length; c++) {
preloads[preloads.length] = new Image();
preloads[preloads.length - 1].src = arguments[c];
}
}
function rotateImages(flag) {
if (flag == 0)
{
num = num - 1;
if (num < 0)
num = preloads.length;
}
else
{
num = num + 1;
if (num >= preloads.length)
num = 0;
}
if (num == temp) {
rotateImages(1);
} else {
var str = preloads[num].src;
var resArr = str.split("/");
var picName = resArr[resArr.length - 1];
document.getElementById("intro").style.backgroundImage = 'url(./images/slider/' + picName + ')';
temp = num;
setTimeout(function () {
rotateImages(1)
}, speed);
}
}
if (window.addEventListener) {
window.addEventListener('load', function () {
setTimeout(function () {
rotateImages(1)
}, speed)
}, false);
} else {
if (window.attachEvent) {
window.attachEvent('onload', function () {
setTimeout(function () {
rotateImages(1)
}, speed)
});
}
}
</script>
You need to clear the previous timer. Otherwise there will be new timers added with every call to rotateImages(), Save the reference returned from setTimeout() and then use clearTimeout() to clear the timer if it's set
var num = 0;
var temp = 0;
var speed = 5000;
var preloads = [];
var timeout;
preload(
'1.png',
'2.jpg',
'3.jpg',
'4.jpg',
'5.png'
);
function preload() {
for (var c = 0; c < arguments.length; c++) {
preloads[preloads.length] = new Image();
preloads[preloads.length - 1].src = arguments[c];
}
}
function rotateImages(flag) {
if (flag == 0) {
num = num - 1;
if (num < 0)
num = preloads.length;
} else {
num = num + 1;
if (num >= preloads.length)
num = 0;
}
if (num == temp) {
rotateImages(1);
} else {
var str = preloads[num].src;
var resArr = str.split("/");
var picName = resArr[resArr.length - 1];
document.getElementById("intro").style.backgroundImage = 'url(./images/slider/' + picName + ')';
temp = num;
if (!!timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
rotateImages(1);
}, speed);
}
}
if (window.addEventListener) {
window.addEventListener('load', function() {
setTimeout(function() {
rotateImages(1)
}, speed)
}, false);
} else {
if (window.attachEvent) {
window.attachEvent('onload', function() {
setTimeout(function() {
rotateImages(1)
}, speed)
});
}
}

How to upload multiple files with fileupload.js?

!function ($) {
"use strict"; // jshint ;_
/* FILEUPLOAD PUBLIC CLASS DEFINITION
* ================================= */
var Fileupload = function (element, options) {
this.$element = $(element)
this.type = this.$element.data('uploadtype') || (this.$element.find('.thumbnail').length > 0 ? "image" : "file")
this.$input = this.$element.find(':file')
if (this.$input.length === 0) return
this.name = this.$input.attr('name') || options.name
this.$hidden = this.$element.find('input[type=hidden][name="'+this.name+'"]')
if (this.$hidden.length === 0) {
this.$hidden = $('<input type="hidden" />')
this.$element.prepend(this.$hidden)
}
this.$preview = this.$element.find('.fileupload-preview')
var height = this.$preview.css('height')
if (this.$preview.css('display') != 'inline' && height != '0px' && height != 'none') this.$preview.css('line-height', height)
this.original = {
'exists': this.$element.hasClass('fileupload-exists'),
'preview': this.$preview.html(),
'hiddenVal': this.$hidden.val()
}
this.$remove = this.$element.find('[data-dismiss="fileupload"]')
this.$element.find('[data-trigger="fileupload"]').on('click.fileupload', $.proxy(this.trigger, this))
this.listen()
}
Fileupload.prototype = {
listen: function() {
this.$input.on('change.fileupload', $.proxy(this.change, this))
$(this.$input[0].form).on('reset.fileupload', $.proxy(this.reset, this))
if (this.$remove) this.$remove.on('click.fileupload', $.proxy(this.clear, this))
},
change: function(e, invoked) {
if (invoked === 'clear') return
var file = e.target.files !== undefined ? e.target.files[0] : (e.target.value ? { name: e.target.value.replace(/^.+\\/, '') } : null)
if (!file) {
this.clear()
return
}
this.$hidden.val('')
this.$hidden.attr('name', '')
this.$input.attr('name', this.name)
if (this.type === "image" && this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match('image.*') : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof FileReader !== "undefined") {
var reader = new FileReader()
var preview = this.$preview
var element = this.$element
reader.onload = function(e) {
preview.html('<img src="' + e.target.result + '" ' + (preview.css('max-height') != 'none' ? 'style="max-height: ' + preview.css('max-height') + ';"' : '') + ' />')
element.addClass('fileupload-exists').removeClass('fileupload-new')
}
reader.readAsDataURL(file)
} else {
this.$preview.text(file.name)
this.$element.addClass('fileupload-exists').removeClass('fileupload-new')
}
},
clear: function(e) {
this.$hidden.val('')
this.$hidden.attr('name', this.name)
this.$input.attr('name', '')
//ie8+ doesn't support changing the value of input with type=file so clone instead
if (navigator.userAgent.match(/msie/i)){
var inputClone = this.$input.clone(true);
this.$input.after(inputClone);
this.$input.remove();
this.$input = inputClone;
}else{
this.$input.val('')
}
this.$preview.html('')
this.$element.addClass('fileupload-new').removeClass('fileupload-exists')
if (e) {
this.$input.trigger('change', [ 'clear' ])
e.preventDefault()
}
},
reset: function(e) {
this.clear()
this.$hidden.val(this.original.hiddenVal)
this.$preview.html(this.original.preview)
if (this.original.exists) this.$element.addClass('fileupload-exists').removeClass('fileupload-new')
else this.$element.addClass('fileupload-new').removeClass('fileupload-exists')
},
trigger: function(e) {
this.$input.trigger('click')
e.preventDefault()
}
}
/* FILEUPLOAD PLUGIN DEFINITION
* =========================== */
$.fn.fileupload = function (options) {
return this.each(function () {
var $this = $(this)
, data = $this.data('fileupload')
if (!data) $this.data('fileupload', (data = new Fileupload(this, options)))
if (typeof options == 'string') data[options]()
})
}
$.fn.fileupload.Constructor = Fileupload
/* FILEUPLOAD DATA-API
* ================== */
$(document).on('click.fileupload.data-api', '[data-provides="fileupload"]', function (e) {
var $this = $(this)
if ($this.data('fileupload')) return
$this.fileupload($this.data())
var $target = $(e.target).closest('[data-dismiss="fileupload"],[data-trigger="fileupload"]');
if ($target.length > 0) {
$target.trigger('click.fileupload')
e.preventDefault()
}
})
}(window.jQuery);
I am using this js for upload file. with it i can upload and preview only one file but i want to upload multiple file with preview anyone can help me to make it for multiple file upload .
i wanna upload multiple file within a time with preview.
see this example.
<div id="mulitplefileuploader">Upload</div>
<div id="status"></div>
<script>
$(document).ready(function()
{
var settings = {
url: "upload.php",
method: "POST",
allowedTypes:"jpg,png,gif,doc,pdf,zip",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload is success</font>");
},
afterUploadAll:function()
{
alert("all images uploaded!!");
},
onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload is Failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
//php code
$output_dir = "./uploads/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
{
if(!is_array($_FILES["myfile"]['name'])) //single file
{
$RandomNum = time();
$ImageName = $_FILES['myfile']['name'];
$ImageType = $_FILES['myfile']['type']; //"image/png", image/jpeg etc.
if (is_dir($output_dir) && is_writable($output_dir)) {
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $ImageName);
//echo "<br> Error: ".$_FILES["myfile"]["error"];
$ret[$ImageName]= $output_dir.$ImageName;
}
else {
echo 'Upload directory is not writable, or does not exist.';
}
}
else
{
$fileCount = count($_FILES["myfile"]['name']);
for($i=0; $i < $fileCount; $i++)
{
$ImageName = $_FILES['myfile']['name'][$i];
$ImageType = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc.
$ret[$ImageName]= $output_dir.$ImageName;
if (is_dir($output_dir) && is_writable($output_dir)) {
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$ImageName );
}
else {
echo 'Upload directory is multi not writable, or does not exist.';
}
}
}
}
echo json_encode($ret);
}
//js code
/*!
* jQuery Upload File Plugin
* version: 3.1.2
* #requires jQuery v1.5 or later & form plugin
* Copyright (c) 2013 Ravishanker Kusuma
* http://hayageek.com/
*/
(function(b) {
if (b.fn.ajaxForm == undefined) {
b.getScript("http://malsup.github.io/jquery.form.js")
}
var a = {};
a.fileapi = b("<input type='file'/>").get(0).files !== undefined;
a.formdata = window.FormData !== undefined;
b.fn.uploadFile = function(t) {
var r = b.extend({
url: "",
method: "POST",
enctype: "multipart/form-data",
formData: null,
returnType: null,
allowedTypes: "*",
fileName: "file",
formData: {},
dynamicFormData: function() {
return {}
},
maxFileSize: -1,
maxFileCount: -1,
multiple: true,
dragDrop: true,
autoSubmit: true,
showCancel: true,
showAbort: true,
showDone: true,
showDelete: false,
showError: true,
showStatusAfterSuccess: true,
showStatusAfterError: true,
showFileCounter: true,
fileCounterStyle: "). ",
showProgress: false,
onSelect: function(s) {
return true
},
onSubmit: function(s, u) {},
onSuccess: function(u, s, v) {},
onError: function(v, s, u) {},
deleteCallback: false,
afterUploadAll: false,
uploadButtonClass: "upload",
dragDropStr: "<span><b>Drag & Drop Files</b></span>",
abortStr: "Abort",
cancelStr: "Cancel",
deletelStr: "Delete",
doneStr: "Done",
multiDragErrorStr: "Multiple File Drag & Drop is not allowed.",
extErrorStr: "is not allowed. Allowed extensions: ",
sizeErrorStr: "is not allowed. Allowed Max size: ",
uploadErrorStr: "Upload is not allowed",
maxFileCountErrorStr: " is not allowed. Maximum allowed files are:"
}, t);
this.fileCounter = 1;
this.selectedFiles = 0;
this.fCounter = 0;
this.sCounter = 0;
this.tCounter = 0;
var d = "upload-" + (new Date().getTime());
this.formGroup = d;
this.hide();
this.errorLog = b("<div></div>");
this.after(this.errorLog);
this.responses = [];
if (!a.formdata) {
r.dragDrop = false
}
if (!a.formdata) {
r.multiple = false
}
var m = this;
var e = b("<div>" + b(this).html() + "</div>");
b(e).addClass(r.uploadButtonClass);
(function k() {
if (b.fn.ajaxForm) {
if (r.dragDrop) {
var s = b('<div class="ajax-upload-dragdrop" style="vertical-align:top;"></div>');
b(m).before(s);
b(s).append(e);
b(s).append(b(r.dragDropStr));
f(m, r, s)
} else {
b(m).before(e)
}
q(m, d, r, e)
} else {
window.setTimeout(k, 10)
}
})();
this.startUpload = function() {
b("." + this.formGroup).each(function(u, s) {
if (b(this).is("form")) {
b(this).submit()
}
})
};
this.stopUpload = function() {
b(".upload-red").each(function(u, s) {
if (b(this).hasClass(m.formGroup)) {
b(this).click()
}
})
};
this.getResponses = function() {
return this.responses
};
var g = false;
function j() {
if (r.afterUploadAll && !g) {
g = true;
(function s() {
if (m.sCounter != 0 && (m.sCounter + m.fCounter == m.tCounter)) {
r.afterUploadAll(m);
g = false
} else {
window.setTimeout(s, 100)
}
})()
}
}
function f(w, u, v) {
v.on("dragenter", function(s) {
s.stopPropagation();
s.preventDefault();
b(this).css("border", "2px solid #000000")
});
v.on("dragover", function(s) {
s.stopPropagation();
s.preventDefault()
});
v.on("drop", function(x) {
b(this).css("border", "2px solid #000000");
x.preventDefault();
w.errorLog.html("");
var s = x.originalEvent.dataTransfer.files;
if (!u.multiple && s.length > 1) {
if (u.showError) {
b("<div style='color:red;'>" + u.multiDragErrorStr + "</div>").appendTo(w.errorLog)
}
return
}
if (u.onSelect(s) == false) {
return
}
l(u, w, s)
});
b(document).on("dragenter", function(s) {
s.stopPropagation();
s.preventDefault()
});
b(document).on("dragover", function(s) {
s.stopPropagation();
s.preventDefault();
v.css("border", "2px solid #000000")
});
b(document).on("drop", function(s) {
s.stopPropagation();
s.preventDefault();
v.css("border", "2px solid #000000")
})
}
function i(s) {
var v = "";
var u = s / 1024;
if (parseInt(u) > 1024) {
var w = u / 1024;
v = w.toFixed(2) + " MB"
} else {
v = u.toFixed(2) + " KB"
}
return v
}
function o(x) {
var y = [];
if (jQuery.type(x) == "string") {
y = x.split("&")
} else {
y = b.param(x).split("&")
}
var u = y.length;
var s = [];
var w, v;
for (w = 0; w < u; w++) {
y[w] = y[w].replace(/\+/g, " ");
v = y[w].split("=");
s.push([decodeURIComponent(v[0]), decodeURIComponent(v[1])])
}
return s
}
function l(H, B, u) {
for (var C = 0; C < u.length; C++) {
if (!c(B, H, u[C].name)) {
if (H.showError) {
b("<div style='color:red;'><b>" + u[C].name + "</b> " + H.extErrorStr + H.allowedTypes + "</div>").appendTo(B.errorLog)
}
continue
}
if (H.maxFileSize != -1 && u[C].size > H.maxFileSize) {
if (H.showError) {
b("<div style='color:red;'><b>" + u[C].name + "</b> " + H.sizeErrorStr + i(H.maxFileSize) + "</div>").appendTo(B.errorLog)
}
continue
}
if (H.maxFileCount != -1 && B.selectedFiles >= H.maxFileCount) {
if (H.showError) {
b("<div style='color:red;'><b>" + u[C].name + "</b> " + H.maxFileCountErrorStr + H.maxFileCount + "</div>").appendTo(B.errorLog)
}
continue
}
B.selectedFiles++;
var D = H;
var w = new FormData();
var A = H.fileName.replace("[]", "");
w.append(A, u[C]);
var y = H.formData;
if (y) {
var F = o(y);
for (var z = 0; z < F.length; z++) {
if (F[z]) {
w.append(F[z][0], F[z][1])
}
}
}
D.fileData = w;
var E = new p(B, H);
var G = "";
if (H.showFileCounter) {
G = B.fileCounter + H.fileCounterStyle + u[C].name
} else {
G = u[C].name
}
E.filename.html(G);
var v = b("<form style='display:block; position:absolute;left: 150px;' class='" + B.formGroup + "' method='" + H.method + "' action='" + H.url + "' enctype='" + H.enctype + "'></form>");
v.appendTo("body");
var x = [];
x.push(u[C].name);
n(v, D, E, x, B);
B.fileCounter++
}
}
function c(w, v, y) {
var x = v.allowedTypes.toLowerCase().split(",");
var u = y.split(".").pop().toLowerCase();
if (v.allowedTypes != "*" && jQuery.inArray(u, x) < 0) {
return false
}
return true
}
function h(u, w) {
if (u.showFileCounter) {
var v = b(".upload-filename").length;
w.fileCounter = v + 1;
b(".upload-filename").each(function(A, y) {
var s = b(this).html().split(u.fileCounterStyle);
var x = parseInt(s[0]) - 1;
var z = v + u.fileCounterStyle + s[1];
b(this).html(z);
v--
})
}
}
function q(y, B, D, u) {
var A = "ajax-upload-id-" + (new Date().getTime());
var w = b("<form method='" + D.method + "' action='" + D.url + "' enctype='" + D.enctype + "'></form>");
var v = "<input type='file' id='" + A + "' name='" + D.fileName + "'/>";
if (D.multiple) {
if (D.fileName.indexOf("[]") != D.fileName.length - 2) {
D.fileName += "[]"
}
v = "<input type='file' id='" + A + "' name='" + D.fileName + "' multiple/>"
}
var z = b(v).appendTo(w);
z.change(function() {
y.errorLog.html("");
var K = D.allowedTypes.toLowerCase().split(",");
var G = [];
if (this.files) {
for (H = 0; H < this.files.length; H++) {
G.push(this.files[H].name)
}
if (D.onSelect(this.files) == false) {
return
}
} else {
var I = b(this).val();
var F = [];
G.push(I);
if (!c(y, D, I)) {
if (D.showError) {
b("<div style='color:red;'><b>" + I + "</b> " + D.extErrorStr + D.allowedTypes + "</div>").appendTo(y.errorLog)
}
return
}
F.push({
name: I,
size: "NA"
});
if (D.onSelect(F) == false) {
return
}
}
h(D, y);
u.unbind("click");
w.hide();
q(y, B, D, u);
w.addClass(B);
if (a.fileapi && a.formdata) {
w.removeClass(B);
var J = this.files;
l(D, y, J)
} else {
var E = "";
for (var H = 0; H < G.length; H++) {
if (D.showFileCounter) {
E += y.fileCounter + D.fileCounterStyle + G[H] + "<br>"
} else {
E += G[H] + "<br>"
}
y.fileCounter++
}
if (D.maxFileCount != -1 && (y.selectedFiles + G.length) > D.maxFileCount) {
if (D.showError) {
b("<div style='color:red;'><b>" + E + "</b> " + D.maxFileCountErrorStr + D.maxFileCount + "</div>").appendTo(y.errorLog)
}
return
}
y.selectedFiles += G.length;
var s = new p(y, D);
s.filename.html(E);
n(w, D, s, G, y)
}
});
w.css({
margin: 0,
padding: 0
});
var C = b(u).width() + 10;
if (C == 10) {
C = 120
}
var x = u.height() + 10;
if (x == 10) {
x = 35
}
u.css({
position: "relative",
overflow: "hidden",
cursor: "default"
});
z.css({
position: "absolute",
cursor: "pointer",
top: "0px",
width: C,
height: x,
left: "0px",
"z-index": "100",
opacity: "0.0",
filter: "alpha(opacity=0)",
"-ms-filter": "alpha(opacity=0)",
"-khtml-opacity": "0.0",
"-moz-opacity": "0.0"
});
w.appendTo(u)
}
function p(v, u) {
//console.log(this);
this.statusbar = b("<div class='upload-statusbar'></div>");
this.filename = b("<div class='upload-filename'></div>").appendTo(this.statusbar);
this.progressDiv = b("<div class='upload-progress'>").appendTo(this.statusbar).hide();
this.progressbar = b("<div class='upload-bar " + v.formGroup + "'></div>").appendTo(this.progressDiv);
this.abort = b("<div class='upload-red " + v.formGroup + "'>" + u.abortStr + "</div>").appendTo(this.statusbar).hide();
this.cancel = b("<div class='upload-red'>" + u.cancelStr + "</div>").appendTo(this.statusbar).hide();
this.done = b("<div class='upload-green'>" + u.doneStr + "</div>").appendTo(this.statusbar).hide();
this.del = b("<div class='upload-red'>" + u.deletelStr + "</div>").appendTo(this.statusbar).hide();
v.errorLog.after(this.statusbar);
return this
}
function n(z, y, u, w, A) {
var x = null;
var v = {
cache: false,
contentType: false,
processData: false,
forceSync: false,
data: y.formData,
formData: y.fileData,
dataType: y.returnType,
beforeSubmit: function(F, C, E) {
if (y.onSubmit.call(this, w) != false) {
var B = y.dynamicFormData();
if (B) {
var s = o(B);
if (s) {
for (var D = 0; D < s.length; D++) {
if (s[D]) {
if (y.fileData != undefined) {
E.formData.append(s[D][0], s[D][1])
} else {
E.data[s[D][0]] = s[D][1]
}
}
}
}
}
A.tCounter += w.length;
j();
return true
}
u.statusbar.append("<div style='color:red;'>" + y.uploadErrorStr + "</div>");
u.cancel.show();
z.remove();
u.cancel.click(function() {
u.statusbar.remove()
});
return false
},
beforeSend: function(B, s) {
u.progressDiv.show();
u.cancel.hide();
u.done.hide();
if (y.showAbort) {
u.abort.show();
u.abort.click(function() {
B.abort();
A.selectedFiles -= w.length
})
}
if (!a.formdata) {
u.progressbar.width("5%")
} else {
u.progressbar.width("1%")
}
},
uploadProgress: function(E, s, D, C) {
if (C > 98) {
C = 98
}
var B = C + "%";
if (C > 1) {
u.progressbar.width(B)
}
if (y.showProgress) {
u.progressbar.html(B);
u.progressbar.css("text-align", "center")
}
},
success: function(B, s, C) {
A.responses.push(B);
u.progressbar.width("100%");
if (y.showProgress) {
u.progressbar.html("100%");
u.progressbar.css("text-align", "center")
}
u.abort.hide();
y.onSuccess.call(this, w, B, C);
if (y.showStatusAfterSuccess) {
if (y.showDone) {
u.done.show();
u.done.click(function() {
u.statusbar.hide("slow");
u.statusbar.remove()
})
} else {
u.done.hide()
}
if (y.showDelete) {
u.del.show();
u.del.click(function() {
u.statusbar.hide().remove();
if (y.deleteCallback) {
y.deleteCallback.call(this, B, u)
}
A.selectedFiles -= w.length;
h(y, A)
})
} else {
u.del.hide()
}
} else {
u.statusbar.hide("slow");
u.statusbar.remove()
}
z.remove();
A.sCounter += w.length
},
error: function(C, s, B) {
u.abort.hide();
if (C.statusText == "abort") {
u.statusbar.hide("slow").remove();
h(y, A)
} else {
y.onError.call(this, w, s, B);
if (y.showStatusAfterError) {
u.progressDiv.hide();
u.statusbar.append("<span style='color:red;'>ERROR: " + B + "</span>")
} else {
u.statusbar.hide();
u.statusbar.remove()
}
A.selectedFiles -= w.length
}
z.remove();
A.fCounter += w.length
}
};
if (y.autoSubmit) {
z.ajaxSubmit(v)
} else {
if (y.showCancel) {
u.cancel.show();
u.cancel.click(function() {
z.remove();
u.statusbar.remove();
A.selectedFiles -= w.length;
h(y, A)
})
}
z.ajaxForm(v)
}
}
return this
}
}(jQuery));

How to implement ipad-like password field behaviour in a text input field using jquery

Is there any plugin similar to the iPad-like password field behaviour. We need to show only the focus number that the customer enters when they enter their credit card number, and then switch to a bullet once the customer types the next number.
For numbers that have been entered prior to the number being entered, they all need to be changed to the bullet style.
Not sure about Jquery plugin. tried this out. Hope this works for you - http://jsfiddle.net/Lhw7xcy6/12/
(function () {
var config = {},
bulletsInProgress = false,
bulletTimeout = null,
defaultOpts = {
className: 'input-long',
maxLength: '16',
type: 'tel',
autoComplete: 'off'
};
var generateBullets = function (n) {
var bullets = '';
for (var i = 0; i < n; i++) {
bullets += "\u25CF";
}
return bullets;
},
getCursorPosition = function (elem) {
var el = $(elem).get(0);
var pos = 0;
var posEnd = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
posEnd = Sel.text.length;
}
return [pos, posEnd];
},
keyInputHandler = function (e, elem, $inpField) {
var keyCode = e.which || e.keyCode,
timeOut = 0,
$bulletField = $(elem),
tempInp = $bulletField.data('tempInp'),
numBullets = $bulletField.data('numBullets');
var position = getCursorPosition(elem);
if (keyCode >= 48 && keyCode <= 57) {
e.preventDefault();
clearTimeout(bulletTimeout);
$bulletField.val(generateBullets(numBullets) + String.fromCharCode(keyCode));
tempInp += String.fromCharCode(keyCode);
numBullets += 1;
bulletsInProgress = true;
timeOut = 3000;
} else if (keyCode == 8) {
clearTimeout(bulletTimeout);
tempInp = (position[0] == position[1]) ? tempInp.substring(0, position[0] - 1) + tempInp.substring(position[1]) : tempInp.substring(0, position[0]) + tempInp.substring(position[1]);
numBullets = (position[0] == position[1]) ? numBullets - 1 : numBullets - (position[1] - position[0]);
tempInp = ($.trim($bulletField.val()) === '') ? '' : tempInp;
numBullets = ($.trim($bulletField.val()) === '') ? 0 : numBullets;
timeOut = 0;
} else {
e.preventDefault();
return false;
}
$bulletField.data('numBullets', numBullets);
$bulletField.data('tempInp', tempInp);
$inpField.val(tempInp);
$('#output').val(tempInp); // testing purpose
bulletTimeout = setTimeout(function () {
$bulletField.val(generateBullets(numBullets));
bulletsInProgress = false;
}, timeOut);
};
$.fn.bulletField = function (options) {
var opts = $.extend({}, defaultOpts, options);
//console.log(opts);
this.each(function () {
var $inpField = $(this),
id = $inpField.attr('id');
$inpField.after('<input id="bullet_' + id + '" type=' + opts.type + ' maxlength=' + opts.maxLength + ' autocomplete=' + opts.autoComplete + ' class=' + opts.className + '>');
$inpField.hide();
var bulletFieldId = 'bullet_' + id;
var $bulletField = $('#' + bulletFieldId);
$bulletField.data('numBullets', 0);
$bulletField.data('tempInp', '');
$('#' + bulletFieldId).on('keydown', function (e) {
keyInputHandler(e, this, $inpField);
});
$('#' + bulletFieldId).on('blur', function () {
//$inpField.trigger('blur');
});
});
return this;
};
}());
$(function () {
/*USAGE - invoke the plugin appropriately whenever needed. example -onclick,onfocus,mousedown etc.*/
//$('body').on('mousedown', '#bulletField', function () {
$('#bulletField').bulletField();
//$('body').off('mousedown');
// });
/* ---OR ----
$('#bulletField').bulletField({
className: 'input-short',
maxLength : '4'
});*/
});

Popunder script that works on all mobiles

I have tested around 15 different popunder scripts to find one that works on all mobiles. The following script is the best one I've found and works perfectly on my Galaxy S3 but annoyingly pops-over on a Galaxy S5. I need the script to popunder on any action on the screen, so that it opens in the background without interfering with the current page. This script has everything I need aside from the fact it behaves differently depending on what Android device it's run on. Can anyone please assist in editing this JavaScript code so it pops-under on all Android browsers and not just some?
Here is the code:
var puShown = false;
var PopWidth = 1370;
var PopHeight = 800;
var PopFocus = 0;
var _Top = null;
function GetWindowHeight() {
var myHeight = 0;
if (typeof(_Top.window.innerHeight) == 'number') {
myHeight = _Top.window.innerHeight;
} else if (_Top.document.documentElement && _Top.document.documentElement.clientHeight) {
myHeight = _Top.document.documentElement.clientHeight;
} else if (_Top.document.body && _Top.document.body.clientHeight) {
myHeight = _Top.document.body.clientHeight;
}
return myHeight;
}
function GetWindowWidth() {
var myWidth = 0;
if (typeof(_Top.window.innerWidth) == 'number') {
myWidth = _Top.window.innerWidth;
} else if (_Top.document.documentElement && _Top.document.documentElement.clientWidth) {
myWidth = _Top.document.documentElement.clientWidth;
} else if (_Top.document.body && _Top.document.body.clientWidth) {
myWidth = _Top.document.body.clientWidth;
}
return myWidth;
}
function GetWindowTop() {
return (_Top.window.screenTop != undefined) ? _Top.window.screenTop : _Top.window.screenY;
}
function GetWindowLeft() {
return (_Top.window.screenLeft != undefined) ? _Top.window.screenLeft : _Top.window.screenX;
}
function doOpen(url) {
var popURL = "about:blank"
var popID = "ad_" + Math.floor(89999999 * Math.random() + 10000000);
var pxLeft = 0;
var pxTop = 0;
pxLeft = (GetWindowLeft() + (GetWindowWidth() / 2) - (PopWidth / 2));
pxTop = (GetWindowTop() + (GetWindowHeight() / 2) - (PopHeight / 2));
if (puShown == true) {
return true;
}
var PopWin = _Top.window.open(popURL, popID, 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,top=' + pxTop + ',left=' + pxLeft + ',width=' + PopWidth + ',height=' + PopHeight);
if (PopWin) {
puShown = true;
if (PopFocus == 0) {
PopWin.blur();
if (navigator.userAgent.toLowerCase().indexOf("applewebkit") > -1) {
_Top.window.blur();
_Top.window.focus();
}
}
PopWin.Init = function(e) {
with(e) {
Params = e.Params;
Main = function() {
if (typeof window.mozPaintCount != "undefined") {
var x = window.open("about:blank");
x.close();
}
var popURL = Params.PopURL;
try {
opener.window.focus();
} catch (err) {}
window.location = popURL;
}
Main();
}
};
PopWin.Params = {
PopURL: url
}
PopWin.Init(PopWin);
}
return PopWin;
}
function setCookie(name, value, time) {
var expires = new Date();
expires.setTime(expires.getTime() + time);
document.cookie = name + '=' + value + '; path=/;' + '; expires=' + expires.toGMTString();
}
function getCookie(name) {
var cookies = document.cookie.toString().split('; ');
var cookie, c_name, c_value;
for (var n = 0; n < cookies.length; n++) {
cookie = cookies[n].split('=');
c_name = cookie[0];
c_value = cookie[1];
if (c_name == name) {
return c_value;
}
}
return null;
}
function initPu() {
_Top = self;
if (top != self) {
try {
if (top.document.location.toString())
_Top = top;
} catch (err) {}
}
if (document.attachEvent) {
document.attachEvent('onclick', checkTarget);
} else if (document.addEventListener) {
document.addEventListener('click', checkTarget, false);
}
}
function checkTarget(e) {
if (!getCookie('popundr')) {
var e = e || window.event;
var win = doOpen('http://www.mediamoby.com/4g9s0hc8/');
setCookie('popundr', 1, 24 * 60 * 60 * 1000);
}
}
initPu();

Categories