I have a youtube API Iframe that loads on a video trimming script.
Works fine but How can I trigger it based on a click function instead of default on document load.
The reason behind this is that I would like to insert a youtube link in an input box and on click I m trying to update the link ID in onYouTubeIframeAPIReady() videoId var.
Here's the fiddle to play around
Here's the code snippet.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/8.5.1/nouislider.min.css'>
<style>
.size
{
font-size: 80px;
font-weight: bold;
}
.sizePar
{
font-size: 21px;
}
.input-size
{
width: 355px;
float: left;
}
.button-size
{
width: 95px;
float: none;
height: 33px;
}
.padding
{
padding-top: 11px;
}
.video-image-size
{
width:250px;
height:auto;
}
.center
{
text-align: center;
padding-top: 25px;
}
.button-rule
{
font-style: normal;
font-weight: bold;
vertical-align: middle;
}
.button-widht
{
width: 116px;
}
.allontana
{
margin-bottom: 30px;
margin-top:50px;
margin-right:15px;
}
.separa{
margin-left: 10px;
margin-right: 10px;
}
.bordered{
border: 1px solid black;
}
body {
padding-top: 70px;
}
.carousel-inner img{
margin: 0 auto;
}
.navbar-brand{
font-size: 20pt;
font-style: bold;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid orange;
margin: 1em 0; padding: 0;
}
.progress {
border-radius: 0px;
height: 10px;
}
.progress-bar-warning{
background: #ffffff;
}
.video-image-size-onWatch{
width:150px;
height:auto;
}
#showcase {
margin: 0 20px;
text-align: center;
}
#range .noUi-base {
}
#range .noUi-background {
}
#range .noUi-connect {
background: #80C9F5;
box-shadow: inset 0 0 5px rgba(20,20,20,0.65);
}
#value-span,
#value-input {
width: 50%;
float: left;
display: block;
text-align: center;
margin: 0;
}
</style>
</head>
<body translate="no" >
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div>
<input type="text" id="custom_link" />
<a id="custom_link_btn" >Submit</a>
</div>
<div class="row">
<div class="col-md-3 text-center">
<hr>
<h3>Cut This Video</h3>
<div class="panel panel-info" style="margin-top:30px;">
<div class="panel-heading">
<h3 class="panel-title">Current Time</h3>
</div>
<div class="panel-body">
<div id="curTime" style="font-size:20px;">
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Select Quality</h3>
</div>
<div class="panel-body">
<div class="dropdown" id="dropdown" style="font-size:20px;">
<!-- dropdown here -->
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Cutted duration</h3>
</div>
<div class="panel-body">
<div id="finalDuration" style="font-size:20px;">
</div>
</div>
</div>
</div>
<!-- player -->
<div class="col-md-6 text-center" style="padding-top:30px;">
<div class="embed-responsive embed-responsive-16by9">
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player" class="embed-responsive-item">
</div>
</div>
<!-- progress bar -->
<div class="progress">
<div class="progress-bar progress-bar-primary progress-bar-striped" id="cut-left" style="width: 0%">
<span class="sr-only"></span>
</div>
<div class="progress-bar progress-bar-success progress-bar-striped active" id="played" style="width: 0%">
<span class="sr-only"></span>
</div>
<div class="progress-bar progress-bar-warning progress-bar-striped" id="toPlay" style="width: 100%">
<span class="sr-only"></span>
</div>
<div class="progress-bar progress-bar-primary progress-bar-striped" id="cut-right" style="width: 0%">
<span class="sr-only"></span>
</div>
</div>
<!-- 2. The IONrangeSlider container -->
<div id="range"></div>
<div id="value-input"></div>
<div id="value-span"></div>
<!-- Controls -->
<div id="controls" style="padding-top:20px;">
<a href="#" onClick="rewindVideo()" class="separa">
<i class="separa fa fa-refresh fa-2x"></i>
</a>
<a href="#" onClick="backwardVideo()" class="separa">
<i class="separa fa fa-backward fa-2x"></i>
</a>
<a href="#" onClick="playPauseVideo()" id="playPause" class="separa">
<i class="separa fa fa-play fa-2x"></i>
</a>
<a href="#" onClick="forwardVideo()" class="separa">
<i class="separa fa fa-forward fa-2x"></i>
</a>
</div>
<div class="input-group" style="margin-top:30px;">
<span class="input-group-addon" id="basic-addon1">Title</span>
<input type="text" name="title" id="title" class="form-control" value="Bill Maher Live DNC Special Edition: July 27" aria-describedby="basic-addon1" required>
<div id="inputList"></div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-6 text-center" style="padding-top: 30px;">
<button type="submit" class="btn btn-primary" style="margin-top:10px">Cut</button>
</div>
<div class="col-md-3">
</div>
</div>
</div>
<!-- endRow -->
<script src="https://cpwebassets.codepen.io/assets/common/stopExecutionOnTimeout-1b93190375e9ccc259df3a57c1abc0e64599724ae30d7ea4c6877eb615f89387.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/8.5.1/nouislider.min.js'></script>
<script id="rendered-js" >
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var duration;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'IP1kr0SCYzk',
playerVars: { 'start': 0, 'autoplay': 0, 'controls': 0 },
events: {
'onReady': onPlayerReady,
'onStateChange': onytplayerStateChange } });
}
function onPlayerReady(event) {
// event.target.playVideo();
duration = player.getDuration();
setMoreInfo();
playPauseVideo();
setIONrangeSlider();
checkDomainAndStop();
}
function onytplayerStateChange(newState) {
setCorrectImageOnPlay();
}
/*
IONrangeSlider
*/
var fromOld = 0;
var toOld = duration;
var slider;
function setIONrangeSlider() {
var slider = document.getElementById('range');
noUiSlider.create(slider, {
start: [0, duration], // Handle start position
step: 1, // Slider moves in increments of '1'
margin: 3, // Handles must be more than '3' apart
connect: true, // Display a colored bar between the handles
behaviour: 'tap-drag', // Move handle on tap, bar is draggable
range: { // Slider can select '0' to 'duration'
'min': 0,
'max': duration } });
var valueInput = document.getElementById('value-input'),
valueSpan = document.getElementById('value-span');
var readValue;
// When the slider value changes, update the input and span
slider.noUiSlider.on('update', function (values, handle) {
if (handle) {
readValue = values[handle] | 0;
valueSpan.innerHTML = toHHMMSS(values[handle]);
if (toOld != readValue) {
toOld = readValue;
}
} else {
readValue = values[handle] | 0;
valueInput.innerHTML = toHHMMSS(values[handle]);
if (fromOld != readValue) {
fromOld = readValue;
player.seekTo(readValue, true);
player.pauseVideo();
player.playVideo();
}
}
});
// When the input changes, set the slider value
valueInput.addEventListener('change', function () {
slider.noUiSlider.set([null, this.value]);
});
}
/*
Player Bar
*/
function updatePlayerBar() {
var curTime = player.getCurrentTime();
var cutLeft = fromOld * 100 / duration;
var cutRigth = (duration - toOld) * 100 / duration;
var played = (curTime - fromOld) * 100 / duration;
var toPlay = 100 - played - cutLeft - cutRigth;
document.getElementById("cut-left").style.width = cutLeft + "%";
document.getElementById("cut-right").style.width = cutRigth + "%";
document.getElementById("played").style.width = played + "%";
document.getElementById("toPlay").style.width = toPlay + "%";
}
/*
Updates the playback quality
*/
function updatePlaybackQuality(quality) {
player.setPlaybackQuality(quality);
waitForQuality(quality);
}
function waitForQuality(quality) {
if (player.getPlaybackQuality() != quality) {
setTimeout(function () {waitForQuality(quality);}, 1000);
} else
{
createQualityList(qualityLevels);
}
}
function checkDomainAndStop() {
var curTime = player.getCurrentTime();
document.getElementById('curTime').innerHTML = toHHMMSS(curTime.toString()) + " / " + toHHMMSS(duration.toString());
var result = toHHMMSS((toOld - fromOld).toString());
if (result != "NaN:NaN:NaN") {
document.getElementById('finalDuration').innerHTML = result;
}
if (curTime < fromOld) {
player.seekTo(fromOld, true);
}
if (curTime > toOld) {
player.seekTo(toOld, true);
pauseVideo();
}
updatePlayerBar();
// recursively call it.
setTimeout(checkDomainAndStop, 100);
}
/*
Setting more infos
*/
var waitForLevels;
var qualityLevels;
function setMoreInfo() {
waitForLevels = player.getAvailableQualityLevels();
if (waitForLevels.length == 0) {
setTimeout(setMoreInfo, 1000);
} else
{
qualityLevels = waitForLevels;
//console.log(qualityLevels);
createQualityList(qualityLevels);
}
}
/*
converts String to hh:mm:ss or mm:ss
*/
function toHHMMSS(val) {
var sec_num = parseInt(val, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - hours * 3600) / 60);
var seconds = sec_num - hours * 3600 - minutes * 60;
if (hours < 10) {hours = "0" + hours;}
if (minutes < 10) {minutes = "0" + minutes;}
if (seconds < 10) {seconds = "0" + seconds;}
// only mm:ss
if (hours == "00") {
var time = minutes + ':' + seconds;
} else
{
var time = hours + ':' + minutes + ':' + seconds;
}
return time;
}
function stopVideo() {
player.stopVideo();
}
function pauseVideo() {
player.pauseVideo();
}
function playVideo() {
player.playVideo();
}
function playPauseVideo() {
//is playing
if (player.getPlayerState() == 1) {
pauseVideo();
} else
{
playVideo();
}
}
function setCorrectImageOnPlay() {
//is playing
if (player.getPlayerState() == 1) {
document.getElementById('playPause').innerHTML =
"<i class=\"separa fa fa-pause fa-2x\"></i>";
} else
{
document.getElementById('playPause').innerHTML =
"<i class=\"separa fa fa-play fa-2x\"></i>";
}
}
function backwardVideo() {
var curTime = player.getCurrentTime();
curTime -= 5;
if (curTime < fromOld) {
player.seekTo(fromOld, true);
} else
{
player.seekTo(curTime, true);
}
}
function rewindVideo() {
player.seekTo(fromOld, true);
playVideo();
}
function forwardVideo() {
var curTime = player.getCurrentTime();
curTime += 5;
if (curTime > toOld) {
player.seekTo(toOld, true);
} else
{
player.seekTo(curTime, true);
}
}
//# sourceURL=pen.js
</script>
So, as per the above code, I'm trying to get the input value with the click of submit button and update it on videoId var, so the trimmable video gets updated. as well.
What I tried:
I tried keeping the whole script inside a function and tried "OnClick", It ran till 2nd console.log print.
Related
I have a custom video trimmer snippet from codepen.
Here's the fiddle link to play around
However, I can only be able to trim the video from youtube. How can I trim a local video using the code?
The code goes as :
<!DOCTYPE html>
<html lang="en" >
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/8.5.1/nouislider.min.css'>
<style>
.size
{
font-size: 80px;
font-weight: bold;
}
.sizePar
{
font-size: 21px;
}
.input-size
{
width: 355px;
float: left;
}
.button-size
{
width: 95px;
float: none;
height: 33px;
}
.padding
{
padding-top: 11px;
}
.video-image-size
{
width:250px;
height:auto;
}
.center
{
text-align: center;
padding-top: 25px;
}
.button-rule
{
font-style: normal;
font-weight: bold;
vertical-align: middle;
}
.button-widht
{
width: 116px;
}
.allontana
{
margin-bottom: 30px;
margin-top:50px;
margin-right:15px;
}
.separa{
margin-left: 10px;
margin-right: 10px;
}
.bordered{
border: 1px solid black;
}
body {
padding-top: 70px;
}
.carousel-inner img{
margin: 0 auto;
}
.navbar-brand{
font-size: 20pt;
font-style: bold;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid orange;
margin: 1em 0; padding: 0;
}
.progress {
border-radius: 0px;
height: 10px;
}
.progress-bar-warning{
background: #ffffff;
}
.video-image-size-onWatch{
width:150px;
height:auto;
}
#showcase {
margin: 0 20px;
text-align: center;
}
#range .noUi-base {
}
#range .noUi-background {
}
#range .noUi-connect {
background: #80C9F5;
box-shadow: inset 0 0 5px rgba(20,20,20,0.65);
}
#value-span,
#value-input {
width: 50%;
float: left;
display: block;
text-align: center;
margin: 0;
}
</style>
</head>
<body translate="no" >
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div class="row">
<div class="col-md-3 text-center">
<hr>
<h3>Cut This Video</h3>
<div class="panel panel-info" style="margin-top:30px;">
<div class="panel-heading">
<h3 class="panel-title">Current Time</h3>
</div>
<div class="panel-body">
<div id="curTime" style="font-size:20px;">
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Select Quality</h3>
</div>
<div class="panel-body">
<div class="dropdown" id="dropdown" style="font-size:20px;">
<!-- dropdown here -->
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Cutted duration</h3>
</div>
<div class="panel-body">
<div id="finalDuration" style="font-size:20px;">
</div>
</div>
</div>
</div>
<!-- player -->
<div class="col-md-6 text-center" style="padding-top:30px;">
<div class="embed-responsive embed-responsive-16by9">
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player" class="embed-responsive-item">
</div>
</div>
<!-- progress bar -->
<div class="progress">
<div class="progress-bar progress-bar-primary progress-bar-striped" id="cut-left" style="width: 0%">
<span class="sr-only"></span>
</div>
<div class="progress-bar progress-bar-success progress-bar-striped active" id="played" style="width: 0%">
<span class="sr-only"></span>
</div>
<div class="progress-bar progress-bar-warning progress-bar-striped" id="toPlay" style="width: 100%">
<span class="sr-only"></span>
</div>
<div class="progress-bar progress-bar-primary progress-bar-striped" id="cut-right" style="width: 0%">
<span class="sr-only"></span>
</div>
</div>
<!-- 2. The IONrangeSlider container -->
<div id="range"></div>
<div id="value-input"></div>
<div id="value-span"></div>
<!-- Controls -->
<div id="controls" style="padding-top:20px;">
<a href="#" onClick="rewindVideo()" class="separa">
<i class="separa fa fa-refresh fa-2x"></i>
</a>
<a href="#" onClick="backwardVideo()" class="separa">
<i class="separa fa fa-backward fa-2x"></i>
</a>
<a href="#" onClick="playPauseVideo()" id="playPause" class="separa">
<i class="separa fa fa-play fa-2x"></i>
</a>
<a href="#" onClick="forwardVideo()" class="separa">
<i class="separa fa fa-forward fa-2x"></i>
</a>
</div>
<div class="input-group" style="margin-top:30px;">
<span class="input-group-addon" id="basic-addon1">Title</span>
<input type="text" name="title" id="title" class="form-control" value="Bill Maher Live DNC Special Edition: July 27" aria-describedby="basic-addon1" required>
<div id="inputList"></div>
</div>
<div class="col-md-3">
</div>
<div class="col-md-6 text-center" style="padding-top: 30px;">
<button type="submit" class="btn btn-primary" style="margin-top:10px">Cut</button>
</div>
<div class="col-md-3">
</div>
</div>
</div>
<!-- endRow -->
<script src="https://cpwebassets.codepen.io/assets/common/stopExecutionOnTimeout-1b93190375e9ccc259df3a57c1abc0e64599724ae30d7ea4c6877eb615f89387.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/8.5.1/nouislider.min.js'></script>
<script id="rendered-js" >
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var duration;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'IP1kr0SCYzk',
playerVars: { 'start': 0, 'autoplay': 0, 'controls': 0 },
events: {
'onReady': onPlayerReady,
'onStateChange': onytplayerStateChange } });
}
function onPlayerReady(event) {
// event.target.playVideo();
duration = player.getDuration();
setMoreInfo();
playPauseVideo();
setIONrangeSlider();
checkDomainAndStop();
}
function onytplayerStateChange(newState) {
setCorrectImageOnPlay();
}
/*
IONrangeSlider
*/
var fromOld = 0;
var toOld = duration;
var slider;
function setIONrangeSlider() {
var slider = document.getElementById('range');
noUiSlider.create(slider, {
start: [0, duration], // Handle start position
step: 1, // Slider moves in increments of '1'
margin: 3, // Handles must be more than '3' apart
connect: true, // Display a colored bar between the handles
behaviour: 'tap-drag', // Move handle on tap, bar is draggable
range: { // Slider can select '0' to 'duration'
'min': 0,
'max': duration } });
var valueInput = document.getElementById('value-input'),
valueSpan = document.getElementById('value-span');
var readValue;
// When the slider value changes, update the input and span
slider.noUiSlider.on('update', function (values, handle) {
if (handle) {
readValue = values[handle] | 0;
valueSpan.innerHTML = toHHMMSS(values[handle]);
if (toOld != readValue) {
toOld = readValue;
}
} else {
readValue = values[handle] | 0;
valueInput.innerHTML = toHHMMSS(values[handle]);
if (fromOld != readValue) {
fromOld = readValue;
player.seekTo(readValue, true);
player.pauseVideo();
player.playVideo();
}
}
});
// When the input changes, set the slider value
valueInput.addEventListener('change', function () {
slider.noUiSlider.set([null, this.value]);
});
}
/*
Player Bar
*/
function updatePlayerBar() {
var curTime = player.getCurrentTime();
var cutLeft = fromOld * 100 / duration;
var cutRigth = (duration - toOld) * 100 / duration;
var played = (curTime - fromOld) * 100 / duration;
var toPlay = 100 - played - cutLeft - cutRigth;
document.getElementById("cut-left").style.width = cutLeft + "%";
document.getElementById("cut-right").style.width = cutRigth + "%";
document.getElementById("played").style.width = played + "%";
document.getElementById("toPlay").style.width = toPlay + "%";
}
/*
Updates the playback quality
*/
function updatePlaybackQuality(quality) {
player.setPlaybackQuality(quality);
waitForQuality(quality);
}
function waitForQuality(quality) {
if (player.getPlaybackQuality() != quality) {
setTimeout(function () {waitForQuality(quality);}, 1000);
} else
{
createQualityList(qualityLevels);
}
}
function checkDomainAndStop() {
var curTime = player.getCurrentTime();
document.getElementById('curTime').innerHTML = toHHMMSS(curTime.toString()) + " / " + toHHMMSS(duration.toString());
var result = toHHMMSS((toOld - fromOld).toString());
if (result != "NaN:NaN:NaN") {
document.getElementById('finalDuration').innerHTML = result;
}
if (curTime < fromOld) {
player.seekTo(fromOld, true);
}
if (curTime > toOld) {
player.seekTo(toOld, true);
pauseVideo();
}
updatePlayerBar();
// recursively call it.
setTimeout(checkDomainAndStop, 100);
}
/*
Setting more infos
*/
var waitForLevels;
var qualityLevels;
function setMoreInfo() {
waitForLevels = player.getAvailableQualityLevels();
if (waitForLevels.length == 0) {
setTimeout(setMoreInfo, 1000);
} else
{
qualityLevels = waitForLevels;
//console.log(qualityLevels);
createQualityList(qualityLevels);
}
}
/*
converts String to hh:mm:ss or mm:ss
*/
function toHHMMSS(val) {
var sec_num = parseInt(val, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - hours * 3600) / 60);
var seconds = sec_num - hours * 3600 - minutes * 60;
if (hours < 10) {hours = "0" + hours;}
if (minutes < 10) {minutes = "0" + minutes;}
if (seconds < 10) {seconds = "0" + seconds;}
// only mm:ss
if (hours == "00") {
var time = minutes + ':' + seconds;
} else
{
var time = hours + ':' + minutes + ':' + seconds;
}
return time;
}
function stopVideo() {
player.stopVideo();
}
function pauseVideo() {
player.pauseVideo();
}
function playVideo() {
player.playVideo();
}
function playPauseVideo() {
//is playing
if (player.getPlayerState() == 1) {
pauseVideo();
} else
{
playVideo();
}
}
function setCorrectImageOnPlay() {
//is playing
if (player.getPlayerState() == 1) {
document.getElementById('playPause').innerHTML =
"<i class=\"separa fa fa-pause fa-2x\"></i>";
} else
{
document.getElementById('playPause').innerHTML =
"<i class=\"separa fa fa-play fa-2x\"></i>";
}
}
function backwardVideo() {
var curTime = player.getCurrentTime();
curTime -= 5;
if (curTime < fromOld) {
player.seekTo(fromOld, true);
} else
{
player.seekTo(curTime, true);
}
}
function rewindVideo() {
player.seekTo(fromOld, true);
playVideo();
}
function forwardVideo() {
var curTime = player.getCurrentTime();
curTime += 5;
if (curTime > toOld) {
player.seekTo(toOld, true);
} else
{
player.seekTo(curTime, true);
}
}
//# sourceURL=pen.js
</script>
Things I tried.
Replacing the youtube link in the iframe with the local video path works but it won't have any effect with the trimmer and progress bar
Tried changing the "player" variable in the script, Failed.
Any help is greatly appreciated.
So basically, I have an image upload page where users can upload images.I use laravel for the backend.It hasn't been working since and the server kept returning errors.So I chnaged the post request to GET and I found out that instead of the script sendind something like http://localhost:8000/upload?title='whatever'&body='theimageselected.jpg'
Of course,the title and body values are variables.They will be different according to what the user wants to uploaad..
It sends this:
http://localhost:8000/upload?[object%20Object]&_=1558376643031
Why?
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon" href="https://static.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico" />
<link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111" />
<title>CodePen - Image Upload With Live Preview using FormData</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<style>
.container {
padding-top: 3%;
}
.hide-element {
display: none;
}
.glyphicon-remove-circle {
float: right;
font-size: 2em;
cursor: pointer;
}
/*
* http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/
*/
.btn-file {
position: relative;
overflow: hidden;
/*box-shadow: 10px 10px 5px #888888;*/
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}
.alert,
.well {
box-shadow: 10px 10px 5px;
-moz-box-shadow: 10px 10px 5px;
-webkit-box-shadow: 10px 10px 5px;
}
#uploadDataInfo p {
margin-left: 2%;
margin-top: 3%;
font-size: 1.2em;
}
.media-left #edit {
z-index: 1000;
cursor: pointer;
}
.thumbnail #edit {
position: absolute;
display: inline;
z-index: 1000;
top: 1px;
right: 15px;
cursor: pointer;
}
.thumbnail #delete {
position: absolute;
display: inline;
z-index: 1000;
margin-top: 4%;
top: 20px;
right: 15px;
cursor: pointer;
}
.caption input[type="text"] {
/*width: 80%;*/
}
.thumbnail .fa-check-circle {
color: #006dcc;
*color: #0044cc;
}
.thumbnail .fa-times-circle {
color: #E74C3C;
}
.modal-header .close {
float: right !important;
margin-right: -30px !important;
margin-top: -25px !important;
background-color: white !important;
border-radius: 15px !important;
width: 30px !important;
height: 30px !important;
opacity: 1 !important;
}
.modal-header {
padding: 0px;
min-height: 0px;
}
.modal-dialog {
top: 50px;
}
.media-left img {
cursor: pointer;
}
.label-tags {
font-size: 16px;
padding: 1%;
color: black;
background-color: white;
border: 1px solid blue;
border-radius: 4px;
margin: 3px;
}
.label-tags i {
cursor: pointer;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<div id="individualImagePreview" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class="fa fa-times"></i></button>
</div>
<div class="modal-body">
<img src="" alt="default image" class="img-responsive" id="individualPreview" />
</div>
<div class="modal-footer" id="displayTags">
<div class="pull-left">
</div>
</div>
</div>
</div>
</div>
<div id="progressModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<div id="ajaxLoad">
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemax="100" id="progressIndicator" style="">
<span class="sr-only">45% Complete</span>
</div>
</div>
<i class="fa fa-cog fa-spin fa-4x"></i> </div>
</div>
<div class="modal-footer hide-element">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="container">
<div class="alert hide-element" role="alert" id="errorMessaage"></div>
<div class="alert hide-element" role="alert" id="file-error-message">
<span class='glyphicon glyphicon-remove-circle'></span>
<p></p>
</div>
<form class="well" id="imagesUploadForm">
<label for="file">Select files to upload</label>
<br />
<span class="btn btn-primary btn-file">
Browse <input type="file" multiple="multiple" accept="image/*" id="uploadImages" /></span>
<p class="help-block">
Only jpg,jpeg,png file with maximum size of 2 MB is allowed.
</p>
<button type="button" data-toggle="modal" data-target="#myModal" class="btn btn-lg btn-primary disabled" value="Preview" name="imagesUpload" id="imagesUpload">Preview</button>
</form>
<div id="uploadDataInfo" class="alert hide-element">
<a href="#" class="close" data-dismiss="alert" aria-label="close">
<i class="fa fa-times"></i>
</a>
<p class="" id="toManyFilesUploaded"></p>
<p class="" id="filesCount"></p>
<p class="" id="filesSupported"></p>
<p class="" id="filesUnsupported"></p>
</div>
<div class="hide-element" id="previewImages">
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="0" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags:max of 3 tags.comma seperated </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo0">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete0">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="1" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags: </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo1">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete1">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="2" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags: </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo2">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete2">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="3" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label>
<input type="text" class="form-control" name="description" value="" /></p>
<p><label for="caption">Caption: </label>
<input type="text" class="form-control" name="caption" value="" /></p>
<p><label for="tags">Tags: </label>
<input type="text" class="form-control" name="tags" value="" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo3">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete3">Delete</a>
</div>
</div>
<button class="btn btn-primary pull-left" id="sendImagesToServer" data-toggle="modal" data-target="#progressModal" data-keyboard="false" data-backdrop="static">Update & Preview</button>
</div>
<br /><br />
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class="fa fa-times"></i></button>
</div>
<div class="modal-body">
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner" role="listbox" id="previewItems">
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<div class="modal-footer hide-element">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
<script id="rendered-js">
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip({
html: true });
$('.media').addClass('hide-element');
$('#imagesUploadForm').submit(function (evt) {
evt.preventDefault();
});
$('#edit').click(function () {
console.log('click detected inside circl-o of edit');
$('#edit').toggleClass('fa-circle-o').toggleClass('fa-check-circle');
if ($('#edit').hasClass('fa-check-circle')) {
$('#captionForImage').toggleClass('hide-element');
} else {
$('#captionForImage').toggleClass('hide-element');
}
});
$('#delete').click(function () {
console.log('click detected inside circl-o of delete');
$('#delete').toggleClass('fa-circle-o').toggleClass('fa-times-circle');
});
//namespace variable to determine whether to continue or not
var proceed = true;
//Ensure that FILE API is supported by the browser to proceed
if (proceed) {
var input = "";
var formData = new FormData();
$('input[type=file]').on("change", function (e) {
var counter = 0;
var modalPreviewItems = "";
input = this.files;
$($(this)[0].files).each(function (i, file) {
formData.append("file[]", file);
});
$('#previewImages').removeClass('hide-element');
$('#imagesUpload').removeClass('disabled');
var successUpload = 0;
var failedUpload = 0;
var extraFiles = 2;
var size = input.length;
$(input).each(function () {
var reader = new FileReader();
var uploadImage = this;
console.log(this);
reader.readAsArrayBuffer(this);
reader.onload = function (e) {
var magicNumbers = validateImage.magicNumbersForExtension(e);
var fileSize = validateImage.isUploadedFileSizeValid(uploadImage);
var extension = validateImage.uploadFileExtension(uploadImage);
var isValidImage = validateImage.validateExtensionToMagicNumbers(magicNumbers);
var thumbnail = validateImage.generateThumbnail(uploadImage);
if (fileSize && isValidImage) {
$('#' + counter).parents('.media').removeClass('hide-element');
$('#' + counter).attr('src', thumbnail).height('200');
$('#uploadDataInfo').removeClass('hide-element').addClass('alert-success');
successUpload++;
modalPreviewItems += carouselInsideModal.createItemsForSlider(thumbnail, counter);
} else {
$('#uploadDataInfo').removeClass('hide-element alert-success').addClass('alert-warning');
failedUpload++;
}
counter++;
if (counter === size) {
$('#myCarousel').append(carouselInsideModal.createIndicators(successUpload, "myCarousel"));
$('#previewItems').append(modalPreviewItems);
$('#previewItems .item').first().addClass('active');
$('#carouselIndicators > li').first().addClass('active');
$('#myCarousel').carousel({
interval: 2000,
cycle: true });
if (size > 4) {
$('#toManyFilesUploaded').html("Only files displayed below will be uploaded");
extraFiles = size - 4;
}
$('#filesCount').html(successUpload + " files are ready to upload");
if (failedUpload !== 0 || extraFiles !== 0) {
failedUpload === 0 ? "" : failedUpload;
extraFiles === 0 ? "" : extraFiles;
$('#filesUnsupported').html(failedUpload + extraFiles + " files were not selected for upload");
}
}
};
});
});
$(document).on('click', '.glyphicon-remove-circle', function () {
$('#file-error-message').addClass('hide-element');
});
$("body").on("click", ".media-object", function () {
var image = $(this).attr('src');
$("#individualPreview").attr('src', image);
var tags = [];
var displayTagsWithFormat = "";
$(this).parents('.media').find('input[type="text"]').each(function () {
if ($(this).attr('name') === 'tags') {
tags = $(this).val().split(",");
$.each(tags, function (index) {
displayTagsWithFormat += "<span class = 'label-tags label'>#" + tags[index] + " <i class='fa fa-times'></i></span>";
});
$("#displayTags").html("<div class='pull-left'>" + displayTagsWithFormat + "</div>");
//console.log(tags);
}
});
});
var toBeDeleted = [];
var eachImageValues = [];
$('.media').each(function (index) {
var imagePresent = "";
$("body").on("click", "#delete" + index, function () {
imagePresent = $("#" + index).attr('src');
$("#undo" + index).removeClass('hide-element');
$("#" + index).attr('src', './img/200x200.gif');
$("#delete" + index).addClass('hide-element');
toBeDeleted.push(index);
//console.log(toBeDeleted);
$("#delete" + index).parent().find('input[type="text"]').each(function () {
var attribute = $(this).attr('name');
var attributeValue = $(this).val();
eachImageValues[attribute + index] = attributeValue;
//console.log(eachImageValues);
});
//console.log(toBeDeleted.length);
if (toBeDeleted.length === 4) {
$('#sendImagesToServer').prop('disabled', true).html('No Files to Upload');
} else {
$('#sendImagesToServer').prop('disabled', false).html('Update & Preview');
}
$("#delete" + index).parent().find('input[type="text"]').prop('disabled', true).addClass('disabled');
});
$("body").on("click", "#undo" + index, function () {
$("#" + index).attr('src', imagePresent);
$("#undo" + index).addClass('hide-element');
$("#delete" + index).removeClass('hide-element');
var indexToDelete = toBeDeleted.indexOf(index);
if (indexToDelete > -1) {
toBeDeleted.splice(indexToDelete, 1);
// console.log(toBeDeleted);
$("#delete" + index).parent().find('input[type="text"]').prop('disabled', false).removeClass('disabled');
}
if (toBeDeleted.length === 4) {
$('#sendImagesToServer').prop('disabled', true).html('No Files to Upload');
} else {
$('#sendImagesToServer').prop('disabled', false).html('Update & Preview');
}
});
});
$('body').on("click", "#sendImagesToServer", function () {
var counter = 0;
var imageData = "";
var consolidatedData = [];
$('.media').each(function () {
var description = "";
var caption = "";
var tags = "";
$('.media').find('input[type="text"]').each(function (index) {
if ((index === 0 || index <= 11) && counter <= 11) {
counter++;
var attributeName = "";
var attributeValue = "";
attributeName = $(this).attr('name');
attributeValue = $(this).val();
switch (attributeName) {
case "title":
title = attributeName;
// console.log(description);
break;
case "caption":
body = attributeName;
// console.log(caption);
break;
case "tags":
tags =attributeName;
// console.log(tags);
break;
default:
break;}
if (counter % 3 === 0) {
imageData = new imageInformation(description, caption, tags);
consolidatedData.push(imageData);
//JSON.stringify(consolidatedData);
//console.log(toBeDeleted);
}
}
});
});
imageData = new deleteList(toBeDeleted);
consolidatedData.push(imageData);
var sendData = JSON.stringify(consolidatedData);
formData.append("important", sendData);
$.ajax({
type: 'GET',
url: '/upload',
xhr: function () {
var customXhr = $.ajaxSettings.xhr();
if (customXhr.upload) {
customXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
}
return customXhr;
},
data: {title:"test",body:"body"},
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function (data) {
$('#ajaxLoad').addClass('hide-element');
$('#successResponse').html(data.message);
console.log(data.message + " inside success function");
},
error: function (data) {
$('#successResponse').html(data.responseJSON.message).addClass('label label-danger').css({
'font-size': '18px' });
console.log(data.responseJSON.message + " inside error function");
} });
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$('#progressIndicator').css({
'width': e.loaded });
}
};
//
//console.log(JSON.stringify(consolidatedData));
});
function imageInformation(description, caption, tags) {
this.description = description;
this.title = caption;
this.tags = tags;
this.type = "image";
};
function deleteList(toBeDeleted) {
this.toBeDeleted = toBeDeleted;
};
var validateImage = {
magicNumbersForExtension: function (event) {
var headerArray = new Uint8Array(event.target.result).subarray(0, 4);
var magicNumber = "";
for (var counter = 0; counter < headerArray.length; counter++) {if (window.CP.shouldStopExecution(0)) break;
magicNumber += headerArray[counter].toString(16);
}window.CP.exitedLoop(0);
return magicNumber;
},
isUploadedFileSizeValid: function (fileUploaded) {
var fileSize = fileUploaded.size;
var maximumSize = 2097125;
var isValid = "";
if (fileSize <= maximumSize) {
isValid = true;
} else {
isValid = false;
}
return isValid;
},
uploadFileExtension: function (fileUploaded) {
var fileExtension = "";
var imageType = "";
imageType = fileUploaded.type.toLowerCase();
fileExtension = imageType.substr(imageType.lastIndexOf('/') + 1);
return fileExtension;
},
validateExtensionToMagicNumbers: function (magicNumbers) {
var properExtension = "";
if (magicNumbers.toLowerCase() === "ffd8ffe0" || magicNumbers.toLowerCase() === "ffd8ffe1" ||
magicNumbers.toLowerCase() === "ffd8ffe8" ||
magicNumbers.toLocaleLowerCase() === "89504e47") {
properExtension = true;
} else {
properExtension = false;
}
return properExtension;
},
generateThumbnail: function (uploadImage) {
if (window.URL)
imageSrc = window.URL.createObjectURL(uploadImage);else
imageSrc = window.webkitURL.createObjectURL(uploadImage);
return imageSrc;
} };
var carouselInsideModal = {
createIndicators: function (carouselLength, dataTarget) {
var carouselIndicators = '<ol class = "carousel-indicators" id="carouselIndicators">';
for (var counter = 0; counter < carouselLength; counter++) {if (window.CP.shouldStopExecution(1)) break;
carouselIndicators += '<li data-target = "#' + dataTarget + '"data-slide-to="' + counter + '"></li>';
}window.CP.exitedLoop(1);
carouselIndicators += "</ol>";
return carouselIndicators;
},
createItemsForSlider: function (imgSrc, counter) {
var item = '<div class = "item">' + '<img src="' + imgSrc + '" id="preview' + counter + '" /></div>';
return item;
} };
}
});
//# sourceURL=pen.js
</script>
<script>
$('.laravel-like').on('click', function(){
if($(this).hasClass('disabled'))
return false;
var item_id = $(this).data('item-id');
var vote = $(this).data('vote');
$.ajax({
method: "post",
url: "/",
data: {item_id: item_id, vote: vote},
dataType: "json"
})
.done(function(msg){
if(msg.flag == 1){
if(msg.vote == 1){
$('#'+item_id+'-like').removeClass('outline');
$('#'+item_id+'-dislike').addClass('outline');
}
else if(msg.vote == -1){
$('#'+item_id+'-dislike').removeClass('outline');
$('#'+item_id+'-like').addClass('outline');
}
else if(msg.vote == 0){
$('#'+item_id+'-like').addClass('outline');
$('#'+item_id+'-dislike').addClass('outline');
}
$('#'+item_id+'-total-like').text(msg.totalLike == null ? 0 : msg.totalLike);
$('#'+item_id+'-total-dislike').text(msg.totalDislike == null ? 0 : msg.totalDislike);
}
})
.fail(function(msg){
alert(msg);
});
});
$(document).on('click', '.reply-button', function(){
if($(this).hasClass("disabled"))
return false;
var toggle = $(this).data('toggle');
$("#"+toggle).fadeToggle('normal');
});
$(document).on('submit', '.laravelComment-form', function(){
var thisForm = $(this);
var parent = $(this).data('parent');
var item_id = $(this).data('item');
var comment = $('textarea#'+parent+'-textarea').val();
$.ajax({
method: "get",
url: "/laravellikecomment/comment/add",
data: {parent: parent, comment: comment, item_id: item_id},
dataType: "json"
})
.done(function(msg){
$(thisForm).toggle('normal');
var newComment = '<div class="comment" id="comment-'+msg.id+'" style="display: initial;"><a class="avatar"><img src="'+msg.userPic+'"></a><div class="content"><a class="author">'+msg.userName+'</a><div class="metadata"><span class="date">Today at 5:42PM</span></div><div class="text">'+msg.comment+'</div><div class="actions"><a class="reply reply-button" data-toggle="'+msg.id+'-reply-form">Reply</a></div><form class="ui laravelComment-form form" id="'+msg.id+'-reply-form" data-parent="'+msg.id+'" data-item="'+item_id+'" style="display: none;"><div class="field"><textarea id="'+msg.id+'-textarea" rows="2"></textarea></div><input type="submit" class="ui basic small submit button" value="Reply"></form></div><div class="ui threaded comments" id="'+item_id+'-comment-'+msg.id+'"></div></div>';
$('#'+item_id+'-comment-'+parent).prepend(newComment);
$('textarea#'+parent+'-textarea').val('');
})
.fail(function(msg){
alert(msg);
});
return false;
});
$(document).on('click', '#showComment', function(){
var show = $(this).data("show-comment");
$('.show-'+$(this).data("item-id")+'-'+show).fadeIn('normal');
$(this).data("show-comment", show+1);
$(this).text("Show more");
});
$(document).on('click', '#write-comment', function(){
$($(this).data("form")).show();
});
</script>
</body>
</html>
you can try
data: JSON.stringify({
title: "Test",
body: "test"
}),
I'm trying to create image swap with the progress bar increase/decrease when the button clicked. This first problem is working but the second one is not working. On the second one, image won't swap after the fist button ("mark completed") clicked.
$(document).ready(function($){
var progress = 20;
var picSource = document.getElementById("mark-complete").src;
var notcomplete = "https://www.w3schools.com/images/picture.jpg";
var completed = "https://www.w3schools.com/images/lamp.jpg";
function changePic() {
if (picSource == notcomplete) {
picSource = completed;
} else {
picSource = notcomplete;
}
}
document.getElementById("btn").onclick = function() {
changePic();
document.getElementById("mark-complete").src = picSource;
}
document.getElementById("btn2").onclick = function() {
changePic();
document.getElementById("mark-complete2").src = picSource;
}
$("#pg1 input").on('change', function(){
if ($("#pg1 input").is(":checked") === true) {
progress = progress+5;
$('#blips > .xp-progress').attr("style","width:" + progress + "%");
}
else if ($("#pg1 input").is(":checked") === false) {
progress = progress-5;
$('#blips > .xp-progress').attr("style","width:" + progress + "%");
}
});
$("#pg2 input").on('change', function(){
if ($("#pg2 input").is(":checked") === true) {
progress = progress+5;
$('#blips > .xp-progress').attr("style","width:" + progress + "%");
}
else if ($("#pg2 input").is(":checked") === false) {
progress = progress-5;
$('#blips > .xp-progress').attr("style","width:" + progress + "%");
}
});
});
.xp-progress { background-color: darkred;
height: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blips" class="xp-line">
<div class="xp-progress" role="progressbar" style="width:20%">
<span class="sr-only" style="color:blue;"></span>
</div>
</div>
<img id="mark-complete" src="https://www.w3schools.com/images/picture.jpg" style="width:80px; float: right;">
<hr>
<p></p>
<label id="pg1" style="cursor:pointer;border:2px solid grey; padding: 5px 10px; border-radius: 4px;">Mark Completed!
<input type="checkbox" id="btn" style="display:none;">
</label>
<hr>
<p></p>
<img id="mark-complete2" src="https://www.w3schools.com/images/picture.jpg" style="width:80px; float: right;">
<label id="pg2" style="cursor:pointer;border:2px solid grey; padding: 5px 10px; border-radius: 4px;">Mark Completed!2
<input type="checkbox" id="btn2" style="display:none;">
</label>
I know it has to do with "getelementbyid" but What did i do wrong?
Here is the demo: https://plnkr.co/UGWOqpdeCDhXuS9MMXfI
picSource is always equals to path to your first image (document.getElementById("mark-complete").src).
You need to pass your current image to changePic and compare it on click event. Updated changePic returns needed src for image.
$(document).ready(function($){
var progress = 20;
var notcomplete = "https://www.w3schools.com/images/picture.jpg";
var completed = "https://www.w3schools.com/images/lamp.jpg";
function changePic(source) {
if (source == notcomplete) {
return completed;
} else {
return notcomplete;
}
}
document.getElementById("btn").onclick = function() {
var imgSrc=document.getElementById("mark-complete").src;
document.getElementById("mark-complete").src = changePic(imgSrc);
}
document.getElementById("btn2").onclick = function() {
var imgSrc=document.getElementById("mark-complete2").src;
document.getElementById("mark-complete2").src = changePic(imgSrc);
}
$("#pg1 input").on('change', function(){
if ($("#pg1 input").is(":checked") === true) {
progress = progress+5;
$('#blips > .xp-progress').attr("style","width:" + progress + "%");
}
else if ($("#pg1 input").is(":checked") === false) {
progress = progress-5;
$('#blips > .xp-progress').attr("style","width:" + progress + "%");
}
});
$("#pg2 input").on('change', function(){
if ($("#pg2 input").is(":checked") === true) {
progress = progress+5;
$('#blips > .xp-progress').attr("style","width:" + progress + "%");
}
else if ($("#pg2 input").is(":checked") === false) {
progress = progress-5;
$('#blips > .xp-progress').attr("style","width:" + progress + "%");
}
});
});
.xp-progress { background-color: darkred;
height: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blips" class="xp-line">
<div class="xp-progress" role="progressbar" style="width:20%">
<span class="sr-only" style="color:blue;"></span>
</div>
</div>
<img id="mark-complete" src="https://www.w3schools.com/images/picture.jpg" style="width:80px; float: right;">
<hr>
<p></p>
<label id="pg1" style="cursor:pointer;border:2px solid grey; padding: 5px 10px; border-radius: 4px;">Mark Completed!
<input type="checkbox" id="btn" style="display:none;">
</label>
<hr>
<p></p>
<img id="mark-complete2" src="https://www.w3schools.com/images/picture.jpg" style="width:80px; float: right;">
<label id="pg2" style="cursor:pointer;border:2px solid grey; padding: 5px 10px; border-radius: 4px;">Mark Completed!2
<input type="checkbox" id="btn2" style="display:none;">
</label>
The problem is that picSource remains set to the src of the last image that was changed.
You've made this way more complicated then it has to be, here is a simplified version:
$(function() {
var progress = 20;
var notcomplete = "https://www.w3schools.com/images/picture.jpg";
var completed = "https://www.w3schools.com/images/lamp.jpg";
$("#btn, #btn2").click(function() {
// Get a reference to the appropriate image based on the id of the pushed button.
var $img = this.id === 'btn' ? $("#mark-complete") : $("#mark-complete2");
// Toggle the image.
if ($img.attr("src") === notcomplete) {
$img.attr("src", completed);
} else {
$img.attr("src", notcomplete);
}
});
$("#pg1 input, #pg2 input").on('change', function() {
if ($(this).is(":checked")) {
progress = progress + 5;
} else {
progress = progress - 5;
}
$('#blips > .xp-progress').css("width", progress + "%");
});
});
.xp-progress {
background-color: darkred;
height: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blips" class="xp-line">
<div class="xp-progress" role="progressbar" style="width:20%">
<span class="sr-only" style="color:blue;"></span>
</div>
</div>
<img id="mark-complete" src="https://www.w3schools.com/images/picture.jpg" style="width:80px; float: right;">
<hr>
<p></p>
<label id="pg1" style="cursor:pointer;border:2px solid grey; padding: 5px 10px; border-radius: 4px;">Mark Completed!
<input type="checkbox" id="btn" style="display:none;">
</label>
<hr>
<p></p>
<img id="mark-complete2" src="https://www.w3schools.com/images/picture.jpg" style="width:80px; float: right;">
<label id="pg2" style="cursor:pointer;border:2px solid grey; padding: 5px 10px; border-radius: 4px;">Mark Completed!2
<input type="checkbox" id="btn2" style="display:none;">
</label>
I am working on a small "Picture browser" application in Bootstrap 4 and JavaScript.
As can be seen below, there is a "Prev" and a "Next" button that help navigate through the pictures.
I have bean trying to find a reliable method to make mouse well scrolling function the same as these buttons. Scrolling down would be the equivalent of clicking the "Next" button. Scrolling up would be the equivalent of clicking the "Prev" button.
var picArr = $('#pictures_list li');
// The index of the last element of the array is "maxIndex"
var maxIndex = picArr.length - 1;
// Initialize counter
var counter = 0;
var updateCounter = function(btn) {
var direction = $(btn).data("direction")
if (direction === "left") {
if (counter > 0) {
counter--;
} else {
counter = maxIndex;
}
} else {
if (counter < maxIndex) {
counter++;
} else {
counter = 0;
}
}
}
var showCount = function(container_id) {
var pageCount = counter + 1;
document.getElementById(container_id).innerHTML = "Picture " + pageCount + " of " + picArr.length;
}
var showSlide = function() {
var mTop = (200 * counter) * (-1) + 'px';
$('#pictures_list').animate({
'marginTop': mTop
}, 400);
}
showCount('show_count');
$('#controls button').on('click', function() {
updateCounter(this);
showSlide();
showCount('show_count');
});
document.getElementById("picture_frame").addEventListener("wheel", function() {
updateCounter(this);
showSlide();
showCount('show_count')
});
#picture_frame {
width: 200px;
height: 200px;
margin: 5px auto;
border: 1px solid #ccc;
border-radius: 2px;
overflow: hidden;
}
.controls>div {
display: inline-block;
}
#picture_frame {
height: 200px;
overflow: hidden;
}
#pictures_list {
flex-flow: row wrap;
align-items: stretch;
width: 200px;
}
#pictures_list li {
display: flex;
height: 200px;
flex: 1 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div id="picture_frame">
<ul id="pictures_list" class="list-unstyled d-flex">
<li><img src="https://picsum.photos/200/200
" alt="First picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=east
" alt="Second picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=west
" alt="Third picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=north
" alt="Fourth picture"></li>
</ul>
</div>
<div class="text-center mb-2">
<span class="badge badge-primary" id="show_count"></span>
</div>
<div class="controls text-center">
<div class="btn-group" id="controls">
<button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button>
<button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button>
</div>
</div>
</div>
Firing the showSlide() function on mouse wheel does work, but the transition is too... continuous. I wish it would be identical to the transition triggered by the buttons.
What am I missing?
Here are several solutions:
-- To prevent the scroll from scrolling multiple images, you can use this function:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
See https://davidwalsh.name/javascript-debounce-function
-- You should change the parameter of your function updateCounter so that it takes the direction of scrolling images. (example: boolean: true = next, false = previous)
--To recover the direction of the scroll, refer to this answer : https://stackoverflow.com/a/45719399/4864628
var picArr = $('#pictures_list li');
// The index of the last element of the array is "maxIndex"
var maxIndex = picArr.length - 1;
// Initialize counter
var counter = 0;
var updateCounter = function(direction) {
if (direction) {
if (counter > 0) {
counter--;
} else {
counter = maxIndex;
}
} else {
if (counter < maxIndex) {
counter++;
} else {
counter = 0;
}
}
}
var showCount = function(container_id) {
var pageCount = counter + 1;
document.getElementById(container_id).innerHTML = "Picture " + pageCount + " of " + picArr.length;
}
var showSlide = function() {
var mTop = (200 * counter) * (-1) + 'px';
$('#pictures_list').animate({
'marginTop': mTop
}, 400);
}
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
showCount('show_count');
$('#controls button').on('click', function() {
updateCounter($(this).attr('data-direction') == 'left');
showSlide();
showCount('show_count');
});
var pictureFrame = document.getElementById("picture_frame");
var onScroll = debounce(function(direction) {
updateCounter(direction);
showSlide();
showCount('show_count')
}, 100, true);
pictureFrame.addEventListener("wheel", function(e) {
e.preventDefault();
var delta;
if (event.wheelDelta){
delta = event.wheelDelta;
}else{
delta = -1 * event.deltaY;
}
onScroll(delta >= 0);
});
#picture_frame {
width: 200px;
height: 200px;
margin: 5px auto;
border: 1px solid #ccc;
border-radius: 2px;
overflow: hidden;
}
.controls>div {
display: inline-block;
}
#picture_frame {
height: 200px;
overflow: hidden;
}
#pictures_list {
flex-flow: row wrap;
align-items: stretch;
width: 200px;
}
#pictures_list li {
display: flex;
height: 200px;
flex: 1 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div id="picture_frame">
<ul id="pictures_list" class="list-unstyled d-flex">
<li><img src="https://picsum.photos/200/200
" alt="First picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=east
" alt="Second picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=west
" alt="Third picture"></li>
<li><img src="https://picsum.photos/200/200?gravity=north
" alt="Fourth picture"></li>
</ul>
</div>
<div class="text-center mb-2">
<span class="badge badge-primary" id="show_count"></span>
</div>
<div class="controls text-center">
<div class="btn-group" id="controls">
<button type="button" class="btn btn-primary btn-sm" data-direction="left">Prev</button>
<button type="button" class="btn btn-primary btn-sm" data-direction="right">Next</button>
</div>
</div>
</div>
I have here a blade page on laravel 5.4 that allows users to input survey responses. The system should show a screensaver after being idle for a certain time ie. idle is 5mins. but the screensaver should disappear when somebody interact with the page. but the codes did not function. I've check the console but it has no error in google chrome. (newbie in javascript)
#php
use App\Bus;
use App\Bgcroute;
use App\Surveyquestion;
use App\User;
use Controller\UserController;
#endphp
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BGC Bus Survey Page</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Cookie">
<link rel="stylesheet" href="assets/css/user.css">
<link rel="stylesheet" href="assets/css/Pretty-Footer.css">
<link rel="stylesheet" href="assets/css/Pretty-Header.css">
<link rel="stylesheet" href="assets/css/Hero-Technology.css">
<link rel="stylesheet" href="js-screensaver/screensaver.css">
<script src="js-screensaver/screensaver.js"></script>
<script src="sweetalert2.all.js"></script>
<script src="sweetalert2.min.js"></script>
<link rel="stylesheet" href="sweetalert2.min.js">
<style type="text/css">
.navbar {
margin-bottom: 0;
border-radius: 0;
background-color: #00FFFF;
color: #FFF;
padding: 1 0;
font-size: 1.2em;
border: 0;
}
.navbar-brand {
float: left;
min-height: 55px;
padding: 0 15px;
}
.img-logo{
width: 75px;
height: 60px;
}
.navbar-inverse .navbar-nav .active a, .navbar-inverse .navbar-nav .active a:focus, .navbar-inverse .navbar-nav .active a:hover {
color: #fff;
background-color: #53DFF0;
}
.navbar-inverse .nav-bar-nav li a {
color: #D5D5D5;
}
.avatar{
border-radius: 100%;
max-width: 100px;
clip: rect(10px,60px,50px,10px);
}
.startScreenSaver({
timeout: 5000,
width: 30,
height: 30,
exitTimeout: 1000,
});
</style>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img class="img-logo" src="img/logo.png"></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<form action="{{route('logout')}}" method="post">
{!!csrf_field()!!}
#if(!empty(Auth::user()->image))
<img src="{{ Auth::user()->image }}" class="avatar" alt="" width="60" height="60">
#else
<img src={{ url('uploads/avatar.png') }} class="avatar" alt="" width="60" height="60">
#endif
<b>Your Driver of the Day, {{ Auth::user()->name }}</b>
<button class="btn btn-danger">Log out</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Route/Bus Details
</button>
</form>
</ul>
</div>
</div>
</nav>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Select Your Desire Route</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{ route('surveysubmit') }}" >
<div class="form-group">
<h4>Select Bus</h4>
<select onchange="$('#busid').val(this.value);" class="form-control" >
#php
$display=''; $initbusid = '';
$buses = Bus::where(['archive'=>1])->orderBy('id')->get(['id','busplate']);
foreach($buses as $bus){
if(empty($initbusid)){$initbusid=$bus->id;}
$display .= '<option value='.$bus->id.'>'.$bus->busplate.'</option>';
}
echo $display;
#endphp
</select>
</div>
<div class="form-group">
<h4>Select Route</h4>
<select onchange="$('#routeid').val(this.value);" class="form-control" >
#php
$display2=''; $initrouteid = '';
$bgcroutes = Bgcroute::where(['routeloc'=>1,'archive'=>1])->orderBy('id')->get(['id','bgcbusroute']);
foreach($bgcroutes as $bgcroute){
if(empty($initrouteid)){$initrouteid=$bgcroute->id;}
$display2 .= '<option value='.$bgcroute->id.'>'.$bgcroute->bgcbusroute.'</option>';
}
echo $display2;
#endphp
</select>
</div>
<button type="button" class="btn btn-danger" data-dismiss="modal">Start Survey</button>
</form>
</div>
</div>
</div>
</div>
#php
$questions = Surveyquestion::where('status',1)->get(['squestions','id'])->first();
#endphp
<section class="testimonials"></section>
<div class="jumbotron visible-xs-block visible-sm-block visible-md-block visible-lg-block hero-technology">
<h2 class="bg-success hero-title">{{ $questions->squestions }}</h2>
<p class="visible-xs-block visible-sm-block visible-md-block visible-lg-block visible-xs-inline visible-sm-inline visible-md-inline visible-lg-inline visible-xs-inline-block visible-sm-inline-block visible-md-inline-block visible-lg-inline-block hidden-xs hidden-sm hidden-md hidden-lg hero-subtitle">Nullam id dolor id nibh ultricies vehicula ut id elit. Cras justo odio, dapibus ac facilisis in, egestas eget quam.</p>
<p class="text-primary bg-warning">Help Us Serve You Better</p>
<p></p>
<p class="text-center bg-primary">Rate us. Choose a smiley that Corresponds to your riding experience</p>
<div>
<input type="hidden" name="driverid" id="driverid" value="{{ Auth::user()->id }}"/>
<input type="hidden" name="busid" id="busid" value="{{ $initbusid }}"/>
<input type="hidden" name="routeid" id="routeid" value="{{ $initrouteid }}"/>
<input type="hidden" name="questionid" id="questionid" value="{{ $questions->id }}"/>
<input type="hidden" name="responseid" id="responseid"/>
<table class="table">
<thead>
<tr>
<th class="info visible-xs-block visible-sm-block visible-md-block visible-lg-block visible-xs-inline visible-sm-inline visible-md-inline visible-lg-inline visible-xs-inline-block">
<img class="img-rounded" src="assets/img/person-clipart-silhouette-blue-14518-blue-man-design.png" height="100">
<img src="assets/img/inlove.gif" height="70" id="loveid">
<img src="assets/img/like.gif" height="90" id="likeid">
<img src="assets/img/facepalm.gif" height="70" id="faceid">
<img src="assets/img/cry.gif" height="70" id="cryid">
</th>
<th
class="danger visible-xs-block visible-sm-block visible-md-block visible-lg-block visible-xs-inline visible-sm-inline visible-md-inline visible-lg-inline visible-xs-inline-block">
<img class="img-rounded" src="assets/img/pink-female-symbol-190136.png" width="40" height="100">
<img src="assets/img/inlove.gif" height="70" id="loveid2">
<img src="assets/img/like.gif" height="90" id="likeid2">
<img src="assets/img/facepalm.gif" height="70" id="faceid2">
<img src="assets/img/cry.gif" height="70" id="cryid2">
</th>
</tr>
</thead>
<tbody>
<tr></tr>
<tr></tr>
</tbody>
<caption> </caption>
</table>
</div>
<p>For Comments/Feedback Email us at bgc#bgc.com</p>
</div>
<div class="container">
<div class="table-responsive">
<table class="table">
<thead>
<tr></tr>
</thead>
<tbody>
<tr></tr>
<tr></tr>
</tbody>
</table>
</div>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
});
function surveyvote(){
driverid = $('#driverid').val();
busid = $('#busid').val();
routeid = $('#routeid').val();
questionid = $('#questionid').val();
responseid = $('#responseid').val();
$.ajax({
"type":"get",
"url": "{{ route('surveyvoting') }}",
"data": '&driverid='+driverid+'&busid='+busid+'&routeid='+routeid+'&questionid='+questionid+'&responseid='+responseid,
"success":function(result){
// Do something you want!
swal({
title: 'Thank You!',
//text: 'I will close in 3 seconds.',
timer: 1000,
onOpen: () => {
swal.showLoading()
}
}).then((result) => {
if (
// Read more about handling dismissals
result.dismiss === swal.DismissReason.timer
) {
console.log('I was closed by the timer')
}
})
}
});
}
</script>
<script type="text/javascript">
var screenSaver = {};
function startScreenSaver(options) {
//* attach event listeners to exit screensaver
attachScreenSaverEventListeners();
if(!screenSaver.initiated) {
//* set screensaver options
screenSaver.options = {
timeout: options.timeout || 5000, //* default timer to start screensaver is 10 minutes
width: options.width || 25, //* default width is 25rem
height: options.height || 25, //* default height is 25rem
exitTimeout: options.exitTimeout || null, //* default timer to exit screensaver is disabled
}
//* create elements
var overlay = document.createElement("div");
overlay.setAttribute('class', 'screensaver-overlay');
document.body.appendChild(overlay);
var createBadge = document.createElement("div");
createBadge.setAttribute('id', 'saver-badge');
document.body.appendChild(createBadge);
createBadge.style.width = screenSaver.options.width + 'rem';
createBadge.style.height = screenSaver.options.height + 'rem';
}
document.getElementsByTagName("body")[0].classList.remove('screensaver');
screenSaver.initiated = true;
screenSaver.setTimeoutValue = screenSaver.options.timeout;
screenSaver.setTimeoutExit = screenSaver.options.timeoutExit;
screenSaver.setTimeout = null; //* clear timeout
screenSaver.inProgress = false;
screenSaver.timerStarted = false;
clearTimeout(screenSaver.setTimeout);
screenSaver.setTimeout = setTimeout(function() {
document.getElementsByTagName("body")[0].classList.add('screensaver');
screenSaver.inProgress = true;
var saverBadge = document.getElementById("saver-badge");
clearInterval(screenSaver.setInterval); //* clear badge display interval
screenSaver.setInterval = null;
//* get dimensions in em
var windowHeight = window.outerHeight / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size'));
var windowWidth = window.outerWidth / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size'));
screenSaver.setInterval = setInterval(function() {
if (screenSaver.inProgress === true) {
saverBadge.classList.remove('visible');
setTimeout(function() {
saverBadge.offsetWidth = saverBadge.offsetWidth;
saverBadge.classList.add('visible');
},1);
var saverTopValue = Math.floor(Math.random() * windowHeight) - screenSaver.options.width;
var saverLeftValue = Math.floor(Math.random() * windowWidth) - screenSaver.options.height;
if (saverTopValue <= 0) { //* make sure the badge doesn't go off the screen
saverTopValue = saverTopValue + 15;
}
if (saverLeftValue <= 0) {
saverLeftValue = saverLeftValue + 15;
}
saverBadge.style.top = saverTopValue + 'rem';
saverBadge.style.left = saverLeftValue + 'rem';
if(screenSaver.timerStarted === false && screenSaver.options.exitTimeout != null) {
startScreenSaverTimer();
}
}
}, 6000);
}, screenSaver.setTimeoutValue);
}
function startScreenSaverTimer() {
screenSaver.timerStarted = true;
setTimeout(function() {
stopScreenSaver();
}, screenSaver.setTimeoutExit);
}
function stopScreenSaver() {
startScreenSaver();
clearInterval(screenSaver.setInterval);
document.getElementsByTagName("body")[0].classList.remove('screensaver');
screenSaver.timerStarted = false;
}
function attachScreenSaverEventListeners() {
var events = ['touchstart', 'mousedown', 'mousemove', 'touchmove', 'keypress', 'scroll'];
var resetScreenSaver = function(e) {
if (screenSaver.inProgress) {
e.stopPropagation();
e.preventDefault();
}
clearTimeout(screenSaver.setTimeout);
clearInterval(screenSaver.setInterval);
document.getElementsByTagName("body")[0].classList.remove('screensaver');
startScreenSaver();
}
var checkClick = function(e) {
if (screenSaver.inProgress) {
startScreenSaver();
}
}
var bindEvents = function(eventName) {
document.addEventListener(eventName, screenSaver.initialize);
//* bind click as fallback for touchstart and mousedown
document.addEventListener('click', checkClick);
}
var unbindEvents = function(eventName) {
document.removeEventListener(eventName, screenSaver.initialize);
}
}
</script>
</body>
</html>
Here is the related files that I think that is related on the script or the javascript
css file screensaver.css
body.screensaver #saver-badge {
opacity: 0;
display: block;
position: absolute;
filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12,Color='#444')";
filter: url(#drop-shadow);
-webkit-filter: drop-shadow(12px 12px 20px rgba(0,0,0,0.5));
filter: drop-shadow(12px 12px 20px rgba(0,0,0,0.5));
background: url(../img/vwd.png) center;
background-size: contain;
z-index: 1001;
}
body.screensaver #saver-badge.visible {
-webkit-animation: fadeBadge 6s;
-moz-animation: fadeBadge 6s;
-o-animation: fadeBadge 6s;
animation: fadeBadge 6s;
opacity: 1;
}
body.screensaver .screensaver-overlay {
background: #000;
opacity: .5;
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
z-index: 1000;
}
#saver-badge {
display: none;
}
#-webkit-keyframes fadeBadge {
0% {
opacity: 0;
}
20% {
opacity: 1;
}
80% {
opacity: 1;
}
100% {
opacity: 0;
}
}
#-moz-keyframes fadeBadge {
0% {
opacity: 0;
}
20% {
opacity: 1;
}
80% {
opacity: 1;
}
100% {
opacity: 0;
}
}
#-o-keyframes fadeBadge {
0% {
opacity: 0;
}
20% {
opacity: 1;
}
80% {
opacity: 1;
}
100% {
opacity: 0;
}
}
#keyframes fadeBadge {
0% {
opacity: 0;
}
20% {
opacity: 1;
}
80% {
opacity: 1;
}
100% {
opacity: 0;
}
}
js file
screensaver.js
var screenSaver = {};
function startScreenSaver(options) {
//* attach event listeners to exit screensaver
attachScreenSaverEventListeners();
if(!screenSaver.initiated) {
//* set screensaver options
screenSaver.options = {
timeout: options.timeout || 60000, //* default timer to start screensaver is 10 minutes
width: options.width || 25, //* default width is 25rem
height: options.height || 25, //* default height is 25rem
exitTimeout: options.exitTimeout || null, //* default timer to exit screensaver is disabled
}
//* create elements
var overlay = document.createElement("div");
overlay.setAttribute('class', 'screensaver-overlay');
document.body.appendChild(overlay);
var createBadge = document.createElement("div");
createBadge.setAttribute('id', 'saver-badge');
document.body.appendChild(createBadge);
createBadge.style.width = screenSaver.options.width + 'rem';
createBadge.style.height = screenSaver.options.height + 'rem';
}
document.getElementsByTagName("body")[0].classList.remove('screensaver');
screenSaver.initiated = true;
screenSaver.setTimeoutValue = screenSaver.options.timeout;
screenSaver.setTimeoutExit = screenSaver.options.timeoutExit;
screenSaver.setTimeout = null; //* clear timeout
screenSaver.inProgress = false;
screenSaver.timerStarted = false;
clearTimeout(screenSaver.setTimeout);
screenSaver.setTimeout = setTimeout(function() {
document.getElementsByTagName("body")[0].classList.add('screensaver');
screenSaver.inProgress = true;
var saverBadge = document.getElementById("saver-badge");
clearInterval(screenSaver.setInterval); //* clear badge display interval
screenSaver.setInterval = null;
//* get dimensions in em
var windowHeight = window.outerHeight / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size'));
var windowWidth = window.outerWidth / parseFloat(window.getComputedStyle(document.getElementsByTagName("body")[0], null).getPropertyValue('font-size'));
screenSaver.setInterval = setInterval(function() {
if (screenSaver.inProgress === true) {
saverBadge.classList.remove('visible');
setTimeout(function() {
saverBadge.offsetWidth = saverBadge.offsetWidth;
saverBadge.classList.add('visible');
},1);
var saverTopValue = Math.floor(Math.random() * windowHeight) - screenSaver.options.width;
var saverLeftValue = Math.floor(Math.random() * windowWidth) - screenSaver.options.height;
if (saverTopValue <= 0) { //* make sure the badge doesn't go off the screen
saverTopValue = saverTopValue + 15;
}
if (saverLeftValue <= 0) {
saverLeftValue = saverLeftValue + 15;
}
saverBadge.style.top = saverTopValue + 'rem';
saverBadge.style.left = saverLeftValue + 'rem';
if(screenSaver.timerStarted === false && screenSaver.options.exitTimeout != null) {
startScreenSaverTimer();
}
}
}, 6000);
}, screenSaver.setTimeoutValue);
}
function startScreenSaverTimer() {
screenSaver.timerStarted = true;
setTimeout(function() {
stopScreenSaver();
}, screenSaver.setTimeoutExit);
}
function stopScreenSaver() {
startScreenSaver();
clearInterval(screenSaver.setInterval);
document.getElementsByTagName("body")[0].classList.remove('screensaver');
screenSaver.timerStarted = false;
}
function attachScreenSaverEventListeners() {
var events = ['touchstart', 'mousedown', 'mousemove', 'touchmove', 'keypress', 'scroll'];
var resetScreenSaver = function(e) {
if (screenSaver.inProgress) {
e.stopPropagation();
e.preventDefault();
}
clearTimeout(screenSaver.setTimeout);
clearInterval(screenSaver.setInterval);
document.getElementsByTagName("body")[0].classList.remove('screensaver');
startScreenSaver();
}
var checkClick = function(e) {
if (screenSaver.inProgress) {
startScreenSaver();
}
}
var bindEvents = function(eventName) {
document.addEventListener(eventName, screenSaver.initialize);
//* bind click as fallback for touchstart and mousedown
document.addEventListener('click', checkClick);
}
var unbindEvents = function(eventName) {
document.removeEventListener(eventName, screenSaver.initialize);
}
for (var i=0;i<events.length;i++) {
bindEvents(events[i]);
}
}