Switching from one image to another - html

I'm trying to figure out how to switch from one image to another after 500 ms. What I have currently keeps switching between images, but I want each image to display for 500 ms and to have the second image disappear after that 500 ms instead of having it loop. This is what I have right now:
<html>
<head>
<title>loop</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 500);
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
</script>
</head>
</html>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
</body>
</html>
Can anyone help me fix this? Thank you!

This should do what you want it to do:
<html>
<head>
<title>loop</title>
<script type = "text/javascript">
var images = [];
var x = 0;
var $img = document.getElementById("img");
images[0] = "image1.jpg";
images[1] = "image2.jpg";
function displayNextImage() {
if (++x < images.length) {
$img.src = images[x];
setInterval(displayNextImage, 500);
}
else {
$img.remove();
}
}
function startTimer() {
setInterval(displayNextImage, 500);
}
</script>
</head>
</html>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
</body>
</html>

Related

AmCharts4 - Unable to load file - external JSON file produced from SQL database

I'm struggling to open my json arranged data in AmCharts4. In my previous charts I used very simple script (chart.data = ;), which unfortunately does not work this time. So I'm using chart.dataSource.url function proposed by AmCharts documentation. When, I load example file found on web everything works fine, as soon as I switch to my file the chart is not able to load file. I'm not able to find a similar problem on web, therefore I would be very grateful for help.
Here is my example with working url and my not working file.
Thanks in advance:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<style>
</style>
</head>
<body>
<div id="chartdiv"></div>
</body>
</html>
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/4/core.js"></script>
<script src="https://cdn.amcharts.com/lib/4/charts.js"></script>
<script src="https://cdn.amcharts.com/lib/4/themes/animated.js"></script>
<!-- Chart code -->
<script>
am4core.ready(function() {
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
var chart = am4core.create('chartdiv', am4charts.XYChart)
// Modify chart's colors
chart.colors.list = [
am4core.color("#264B29"),
am4core.color("#94B255"),
am4core.color("#456C39"),
am4core.color("#C4D563"),
am4core.color("#698F47"),
am4core.color("#F9F871"),
];
chart.legend = new am4charts.Legend()
chart.legend.position = 'top'
chart.legend.paddingBottom = 20
chart.legend.labels.template.maxWidth = 95
var xAxis = chart.xAxes.push(new am4charts.CategoryAxis())
xAxis.dataFields.category = 'year'
xAxis.renderer.cellStartLocation = 0.1
xAxis.renderer.cellEndLocation = 0.9
xAxis.renderer.grid.template.location = 0;
var yAxis = chart.yAxes.push(new am4charts.ValueAxis());
function createSeries(value, name) {
var series = chart.series.push(new am4charts.ColumnSeries())
series.dataFields.valueY = value
series.dataFields.categoryX = 'year'
series.name = name
series.events.on("hidden", arrangeColumns);
series.events.on("shown", arrangeColumns);
var bullet = series.bullets.push(new am4charts.LabelBullet())
bullet.interactionsEnabled = false
bullet.dy = 30;
bullet.label.text = '{valueY}'
bullet.label.fill = am4core.color('#ffffff')
return series;
}
// Add data
//Working url
//chart.dataSource.url = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/sample_data_serial.json";
//My SQL produced JSON file is not working
chart.dataSource.url = "data/my-file.php";
chart.dataSource.adapter.add("parsedData", function(data) {
var newData = [];
data.forEach(function(dataItem) {
var newDataItem = {};
Object.keys(dataItem).forEach(function(key) {
if (typeof dataItem[key] === "object") {
newDataItem["_id"] = dataItem[key]["#id"];
dataItem[key]["Column"].forEach(function(dataItem) {
newDataItem[dataItem["#name"]] = dataItem["#id"];
});
} else {
newDataItem[key] = dataItem[key];
}
});
newData.push(newDataItem);
});
data = newData;
return data;
});
createSeries('cars', 'The First');
createSeries('motorcycles', 'The Second');
createSeries('bicycles', 'The Third');
//createSeries('bilanca_lsk_lst', 'T4');
function arrangeColumns() {
var series = chart.series.getIndex(0);
var w = 1 - xAxis.renderer.cellStartLocation - (1 - xAxis.renderer.cellEndLocation);
if (series.dataItems.length > 1) {
var x0 = xAxis.getX(series.dataItems.getIndex(0), "yearX");
var x1 = xAxis.getX(series.dataItems.getIndex(1), "yearX");
var delta = ((x1 - x0) / chart.series.length) * w;
if (am4core.isNumber(delta)) {
var middle = chart.series.length / 2;
var newIndex = 0;
chart.series.each(function(series) {
if (!series.isHidden && !series.isHiding) {
series.dummyData = newIndex;
newIndex++;
}
else {
series.dummyData = chart.series.indexOf(series);
}
})
var visibleCount = newIndex;
var newMiddle = visibleCount / 2;
chart.series.each(function(series) {
var trueIndex = chart.series.indexOf(series);
var newIndex = series.dummyData;
var dx = (newIndex - trueIndex + middle - newMiddle) * delta
series.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
series.bulletsContainer.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
})
}
}
}
});
// end am4core.ready()
</script>
I found a typing error in my-file.php
Anyhow, after I solved typing issue the chart.dataSource.url function still did not work, but It worked using next php include script.
chart.data = <?php include './data/my-file.php'; ?>;

d3 svg transition has slight unwanted horizontal movement on Firefox

The following has some SVG squares that march upwards once per second. In Google Chrome it looks fine. In Firefox, the squares shift right and left by about 1 pixel which is not what I intended.
Can anyone help figure out why?
I'm sorry this code snippet is not simpler; this is about as basic as I could go from a much longer file in which I removed all the unrelated aspects.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
<style type='text/css'>
.hidden {
display: none;
}
#ticktock {
position: absolute;
top: 550px;
left: 400px;
}
svg rect.cell {
fill: none;
stroke: steelblue;
}
</style>
<script type='text/javascript'>
document.addEventListener('DOMContentLoaded',function(event) {
var L = 25;
var maxFacetCount = 8;
var state = {
nexttick: 0,
ticksize: 500,
n: -8,
nx: 8,
wheel: [],
nfacet: maxFacetCount,
init: true,
ticktock: true
};
function update_state(state)
{
if (state.ticktock)
{
if (state.wheel.length >= state.nfacet)
state.wheel.shift();
state.wheel.push({n: ++state.n });
}
}
state.wheel = state.wheel.slice(-1);
function prepare_view(state)
{
var width = 60 + (state.nx+0.5)*(L+2);
var height = 5 + (state.nfacet+0.5)*L;
var svg = d3.select("#wheel-container").append("svg")
.attr("width", width)
.attr("height", height);
var x1 = L*0.5+5;
var wheel = svg.append('g')
.attr('id','wheel')
.attr('transform','translate('+x1+',0)');
}
prepare_view(state);
function facet_enter(facets, t)
{
var facet = facets.append('g');
for (var i = 0; i < state.nx; ++i)
{
facet.append('rect')
.attr('x',i*L)
.attr('y',0)
.attr('width',L)
.attr('height',L)
.attr('class','cell');
}
facet_move(facet, state.init ? null : t);
}
function facet_move(facet, t)
{
(t ? facet.transition(t) : facet)
.attr('opacity',function(d,i) {
var age = state.n - d.n;
return age == 0 ? 0 : 1-age/state.nfacet; })
.attr('transform',function(d,i) { return 'translate(0,'+((d.n-state.n+state.nfacet-1)*L)+')'; });
}
function facet_update(facets, t)
{
facet_move(facets, t);
}
function update_view(state, ticktock)
{
var wheel = d3.select("#wheel");
var facets = wheel.selectAll('g');
if (state.ticktock)
{
var t = d3.transition().duration(300);
var upd = facets
.data(state.wheel, function(d,i) { return d.n; });
upd .call(facet_update, t)
.enter()
.call(facet_enter, t)
upd.exit()
.transition(t)
.attr('transform','translate (0,'+(-L)+')')
.remove();
}
else
{
// tock
var t = d3.transition().duration(100);
var t2 = t.transition().duration(100);
var upd = facets
.data(state.wheel, function(d,i) { return d.n; });
upd.call(facet_update, t)
.enter()
.call(facet_enter, t);
}
}
var tmr = d3.timer(function(elapsed) {
var do_something = false;
while (elapsed >= state.nexttick)
{
do_something = true;
state.nexttick += state.ticksize;
}
if (do_something && !(d3.select('#pause').property('checked') ))
{
state.ticktock = !state.ticktock;
update_state(state);
update_view(state);
state.init = false;
}
} );
});
</script>
</head>
<body>
<div id='wheel-container' ></div>
<form class="">
<input type="checkbox" id="pause" name="pause">pause</input>
</form>
<div id='ticktock' class='hidden'></div>
</body>
</html>
Looks like floating-point rounding errors strike again. I changed to shape-rendering: crispEdges; and then rounded to an integer translate in one of the root elements and that seems to fix most of it (still a little residual y-axis shift).
was:
var x1 = L*0.5+5;
var wheel = svg.append('g')
.attr('id','wheel')
.attr('transform','translate('+x1+',0)');
changed to:
var x1 = Math.round(L*0.5+5);
var wheel = svg.append('g')
.attr('id','wheel')
.attr('transform','translate('+x1+',0)');
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
<style type='text/css'>
.hidden {
display: none;
}
#ticktock {
position: absolute;
top: 550px;
left: 400px;
}
svg rect.cell {
fill: none;
stroke: steelblue;
shape-rendering: crispEdges;
}
</style>
<script type='text/javascript'>
document.addEventListener('DOMContentLoaded',function(event) {
var L = 25;
var maxFacetCount = 8;
var state = {
nexttick: 0,
ticksize: 500,
n: -8,
nx: 8,
wheel: [],
nfacet: maxFacetCount,
init: true,
ticktock: true
};
function update_state(state)
{
if (state.ticktock)
{
if (state.wheel.length >= state.nfacet)
state.wheel.shift();
state.wheel.push({n: ++state.n });
}
}
state.wheel = state.wheel.slice(-1);
function prepare_view(state)
{
var width = 60 + (state.nx+0.5)*(L+2);
var height = 5 + (state.nfacet+0.5)*L;
var svg = d3.select("#wheel-container").append("svg")
.attr("width", width)
.attr("height", height);
var x1 = Math.round(L*0.5+5);
var wheel = svg.append('g')
.attr('id','wheel')
.attr('transform','translate('+x1+',0)');
}
prepare_view(state);
function facet_enter(facets, t)
{
var facet = facets.append('g');
for (var i = 0; i < state.nx; ++i)
{
facet.append('rect')
.attr('x',i*L)
.attr('y',0)
.attr('width',L)
.attr('height',L)
.attr('class','cell');
}
facet_move(facet, state.init ? null : t);
}
function facet_move(facet, t)
{
(t ? facet.transition(t) : facet)
.attr('opacity',function(d,i) {
var age = state.n - d.n;
return age == 0 ? 0 : 1-age/state.nfacet; })
.attr('transform',function(d,i) { return 'translate(0,'+((d.n-state.n+state.nfacet-1)*L)+')'; });
}
function facet_update(facets, t)
{
facet_move(facets, t);
}
function update_view(state, ticktock)
{
var wheel = d3.select("#wheel");
var facets = wheel.selectAll('g');
if (state.ticktock)
{
var t = d3.transition().duration(300);
var upd = facets
.data(state.wheel, function(d,i) { return d.n; });
upd .call(facet_update, t)
.enter()
.call(facet_enter, t)
upd.exit()
.transition(t)
.attr('transform','translate (0,'+(-L)+')')
.remove();
}
else
{
// tock
var t = d3.transition().duration(100);
var t2 = t.transition().duration(100);
var upd = facets
.data(state.wheel, function(d,i) { return d.n; });
upd.call(facet_update, t)
.enter()
.call(facet_enter, t);
}
}
var tmr = d3.timer(function(elapsed) {
var do_something = false;
while (elapsed >= state.nexttick)
{
do_something = true;
state.nexttick += state.ticksize;
}
if (do_something && !(d3.select('#pause').property('checked') ))
{
state.ticktock = !state.ticktock;
update_state(state);
update_view(state);
state.init = false;
}
} );
});
</script>
</head>
<body>
<div id='wheel-container' ></div>
<form class="">
<input type="checkbox" id="pause" name="pause">pause</input>
</form>
<div id='ticktock' class='hidden'></div>
</body>
</html>

jQuery : Dynamic HTML onClick

I am trying to create dynamically generated elements when the user clicks on a button. The should slide in from the right, and when the button is clicked again, another should slide in from the right. For some reason, it is not doing exactly what I need it to do. Here's the code:
<html>
<head>
<title>Chat Head</title>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript" src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
screenWidth = $(window).width();
screenHeight = $(window).height();
msgWidth = 0.7*screenWidth;
msgHeight = 0.7*screenHeight;
$("#note").css("width", msgWidth);
$("#note").css("height", msgHeight);
$("#slide").click(function(){
var textArea = '<textarea class = form-control rows = "3" id = "text"></textarea>';
$(textArea).appendTo('.note');
var effect = 'slide';
var duration = 1000;
$(".note").toggle(effect, {direction: 'right'}, duration);
});
});
</script>
</head>
<style type="text/css">
.note{
display: none;
}
</style>
<body>
<div class="row">
<div class="col-md-12">
<button class = "button" id = "slide">Slide</button>
<hr />
<div class="note">
<!-- <textarea class = "form-control" rows = "2" id = "note"></textarea> -->
</div>
</div>
</div>
</body>
</html>
Here's the JS Fiddle that goes with the code:
http://jsfiddle.net/ma6Jq/2/
Here is an implementation I came up with. http://jsfiddle.net/Ar7qw/1/
<script>
$(document).ready(function(){
var count = 0;
$("#slide").click(function(){
count = count + 1;
screenWidth = $(window).width();
screenHeight = $(window).height();
msgWidth = 0.7*screenWidth;
msgHeight = 0.7*screenHeight;
$("#note"+ count).css("width", msgWidth);
$("#note"+ count).css("height", msgHeight);
var newnote = '<div class="note' + count +'"></div>';
$(newnote).appendTo('.col-md-12');
var textArea = '<textarea class="form-control" rows = "3" id = "text"></textarea>';
$(textArea).appendTo('.note' + count);
$('.note' + count).effect('slide', {direction: 'right'}, 1000);
});
});
</script>
This gets you close. I'm out of time for now.
http://jsfiddle.net/isherwood/ma6Jq/10
.note-box {
margin-left: 150%;
}
.done {
margin-left: 10px;
transition: all 1s;
}
$("#slide").click(function () {
var textArea = '<textarea class="form-control note-box" rows="3"></textarea>';
var duration = 1000;
$(textArea).appendTo('#note').addClass('done', duration);
});
Another implementation for anybody needing one(or a couple different choices of solutions)
http://jsfiddle.net/ma6Jq/13/
var counter = 0;
$("#slide").click(function () {
counter ++;
var textArea = '<div class="note' + counter + '"><textarea class ="form-control" rows = "3" id = "text">'+ counter +'yo</textarea></div>';
$(textArea).appendTo('.note');
var effect = 'slide';
var duration = 1000;
var stringhere = ".note" + counter;
$(stringhere).effect('slide',
{
direction:'right'
}, duration);
/*
$(stringhere).animate({
marginLeft: parseInt($(stringhere).css('marginLeft'),1000) == 0 ?
$(stringhere).outerWidth() :
100
});
*/
/*
$(stringhere).toggle(effect, {
direction: 'left'
}, duration);
*/
});
});

jquery webcam not working in chrome 35

I am trying to access webcam from jquery webcam API. The sample given below works fine in IE9, Firefox, but unfortunately does not work in Chrome v35. It shows the webcam activated but when I click the "Take Picture" button, it gives me a javascript error saying that webcam.capture is undefined. In the code below, the webcam object does not have any function called capture() in chrome; but its found for Firefox and IE9.
Please help me out!!
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.11.0.js"></script>
<script type="text/javascript" src="jquery.webcam.min.js"></script>
</head>
<body>
<p id="status" style="height:22px; color:#c00;font-weight:bold;"></p>
<div id="webcam" style="width:350px;float: left;"">
Take a picture instantly
</div>
<p style="width:350px; float: left;"><canvas id="canvas" height="240" width="320" style="float: left;""></canvas></p>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
main.js
var pos = 0;
var ctx = null;
var cam = null;
var image = null;
var filter_on = false;
var filter_id = 0;
function changeFilter() {
if (filter_on) {
filter_id = (filter_id + 1) & 7;
}
}
function toggleFilter(obj) {
if (filter_on =!filter_on) {
obj.parentNode.style.borderColor = "#c00";
} else {
obj.parentNode.style.borderColor = "#333";
}
}
jQuery("#webcam").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "http://www.xarg.org/download/jscam_canvas_only.swf",
onTick: function(remain) {
if (0 == remain) {
jQuery("#status").text("Cheese!");
} else {
jQuery("#status").text(remain + " seconds remaining...");
}
},
onSave: function(data) {
var col = data.split(";");
var img = image;
for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
}
if (pos >= 0x4B000) {
ctx.putImageData(img, 0, 0);
pos = 0;
}
},
onCapture: function () {
webcam.save();
jQuery("#flash").css("display", "block");
jQuery("#flash").fadeOut(100, function () {
jQuery("#flash").css("opacity", 1);
});
},
debug: function (type, string) {
jQuery("#status").html(type + ": " + string);
},
onLoad: function () {
var cams = webcam.getCameraList();
for(var i in cams) {
jQuery("#cams").append("<li>" + cams[i] + "</li>");
}
}
});
function getPageSize() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
return [pageWidth, pageHeight];
}
window.addEventListener("load", function() {
jQuery("body").append("<div id=\"flash\"></div>");
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
ctx = document.getElementById("canvas").getContext("2d");
ctx.clearRect(0, 0, 320, 240);
var img = new Image();
img.src = "logo.gif";
img.onload = function() {
ctx.drawImage(img, 129, 89);
}
image = ctx.getImageData(0, 0, 320, 240);
}
var pageSize = getPageSize();
jQuery("#flash").css({ height: pageSize[1] + "px" });
}, false);
window.addEventListener("resize", function() {
var pageSize = getPageSize();
jQuery("#flash").css({ height: pageSize[1] + "px" });
}, false);
I think I found the answer. I was initially trying to run the code from a folder location on my system. But when I deployed the same code to a local web application running on tomcat (http://<>/webcam/webcam.html), it started working in chrome!! I was anyhow going to deploy the code tomorrow on a remote server but had no idea that the webcam APIs would be inaccessible from the system if the application is not running on a server. Quite strange, but this saved me!!

Infinite loading

I followed a tutorial for infinite loading. I managed this code, but the background just keeps loading again and again. I want to display my content just once. Can anyone help me please? Here's the code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function yHandler(){
// Watch video for line by line explanation of the code
// http://www.youtube.com/watch?v=eziREnZPml4
var wrap = document.getElementById('wrap');
var contentHeight = wrap.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
// Ajax call to get more dynamic data goes here
wrap.innerHTML += '<div class="newData"></div>';
}
var status = document.getElementById('status');
status.innerHTML = contentHeight+" | "+y;
}
window.onscroll = yHandler;
</script>
<style type="text/css">
div#status{position:fixed; font-size:24px;}
div#wrap{width:800px; margin:0px auto;}
div.newData{height:1000px; background:#09F; margin:10px 0px;}
</style>
</head>
<body>
<div id="status">0 | 0</div>
<div id="wrap"><img src="http://images.bwwstatic.com/tvnetworklogos/1470470F-930B-5791-2D55F77DC33EBA96.jpg"></div>
</body>
</html>
by setting the window.onscroll to null you essentially have a "fire once" event.
<script type="text/javascript">
function yHandler(){
var wrap = document.getElementById('wrap');
var contentHeight = wrap.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
// Ajax call to get more dynamic data goes here
wrap.innerHTML += '<div class="newData"></div>';
window.onscroll = null;
}
var status = document.getElementById('status');
status.innerHTML = contentHeight+" | "+y;
}
window.onscroll = yHandler;
</script>