Limit amount of uploaded Images [duplicate] - javascript

This question already has answers here:
How can restrict user to upload max 10 files at once?
(2 answers)
Closed 2 years ago.
I have this JavaScript code which lets users upload and preview their uploaded images.
The images are being previewed through a table grid with specified dimensions.
My Question:
How can I edit the JavaScript to limit users from uploading more than 9 images?
Note: the same restriction would be implemented on the server side later on. Due to users being able to bypass this JavaScript code. But that's for later. For now I want to get the frontend to limit the users.
Note: This question has been asked before but was based solely on limiting file input button. My problem is implementing this code with mine.
Code in question (to limit file upload)
$(function() {
$("button[type = 'submit']").click(function(event) {
var $fileUpload = $("input[type='file']");
if (parseInt($fileUpload.get(0).files.length) > 10) {
alert("You are only allowed to upload a maximum of 10 files");
event.preventDefault();
}
});
});
(function (global) {
var imagesPerRow = 3,
chooseFiles,
columns,
previews;
function PreviewImages() {
var row;
Array.prototype.forEach.call(chooseFiles.files, function (file, index) {
var cindex = index % imagesPerRow,
oFReader = new FileReader(),
cell,
image;
if (cindex === 0) {
row = previews.insertRow(Math.ceil(index / imagesPerRow));
}
image = document.createElement("img");
image.id = "img_" + index;
image.style.objectFit = "cover";
image.style.width = "150px";
image.style.height = "90px";
cell = row.insertCell(cindex);
cell.appendChild(image);
oFReader.addEventListener("load", function assignImageSrc(evt) {
image.src = evt.target.result;
this.removeEventListener("load", assignImageSrc);
}, false);
oFReader.readAsDataURL(file);
});
}
global.addEventListener("load", function windowLoadHandler() {
global.removeEventListener("load", windowLoadHandler);
chooseFiles = document.getElementById("chooseFiles");
columns = document.getElementById("columns");
previews = document.getElementById("previews");
var row = columns.insertRow(-1),
header,
i;
for (i = 0; i < imagesPerRow; i += 1) {
header = row.insertCell(-1);
header.style.width = (100 / imagesPerRow) + "%";
}
chooseFiles.addEventListener("change", PreviewImages, false);
}, false);
}(window));
div.rounded {
width: 100%;
border-style: solid;
border-width: 1px;
border-radius: 5px;
}
label {
display: block;
}
input {
display: block;
}
#previewTable {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="imagesDiv" class="rounded">
<label for="chooseFiles">Add Images</label>
<input type="file" id="chooseFiles" multiple="multiple" />
<table id="previewTable">
<thead id="columns"></thead>
<tbody id="previews"></tbody>
</table>
</div>

You can modify your javascript code to check the files.length property of the input type="file" element & set the files array empty by assigning the value property of the input element to an empty string if the files.length is more than 9.
check the modified javascript code:
(function (global) {
var imagesPerRow = 3,
chooseFiles,
columns,
previews;
global.addEventListener("load", function windowLoadHandler() {
global.removeEventListener("load", windowLoadHandler);
chooseFiles = document.getElementById("chooseFiles");
columns = document.getElementById("columns");
previews = document.getElementById("previews");
var row = columns.insertRow(-1),
header,
i;
for (i = 0; i < imagesPerRow; i += 1) {
header = row.insertCell(-1);
header.style.width = (100 / imagesPerRow) + "%";
}
chooseFiles.addEventListener("change", function (e) {
if(this.files.length > 9){
alert("You are only allowed to upload a maximum of 9 files");
this.value = "";
e.preventDefault();
}
else{
var row;
Array.prototype.forEach.call(chooseFiles.files, function (file, index) {
var cindex = index % imagesPerRow,
oFReader = new FileReader(),
cell,
image;
if (cindex === 0) {
row = previews.insertRow(Math.ceil(index / imagesPerRow));
}
image = document.createElement("img");
image.id = "img_" + index;
image.style.objectFit = "cover";
image.style.width = "150px";
image.style.height = "90px";
cell = row.insertCell(cindex);
cell.appendChild(image);
oFReader.addEventListener("load", function assignImageSrc(evt) {
image.src = evt.target.result;
this.removeEventListener("load", assignImageSrc);
}, false);
oFReader.readAsDataURL(file);
});
}
}, false);
}, false);
}(window));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive</title>
<link rel="stylesheet" href="./assets/css/custom.css">
</head>
<body>
<div id="imagesDiv" class="rounded">
<label for="chooseFiles">Add Images</label>
<input type="file" id="chooseFiles" multiple="multiple" />
<table id="previewTable">
<thead id="columns"></thead>
<tbody id="previews"></tbody>
</table>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="./assets/js/main.js"></script>
</body>
</html>
Hope this solves your problem.

I can't really understand the code displayed above, but what you can do is:
Define variable uploadedImages = 0 so that every time the user uploads a photo on the website, uploadedImages increments by one. Also, make an IF statement that checks every time before uploading a photo, and only upload the image if the uploadedImages didn't pass the max number of uploaded images allowed.
I tried to implement this in your code but I can't figure out how it works.

Related

How to fetch Google Drive PDF url using pdf.js script on new web page?

I have an example of two websites that uses google drive and whenever they have a new document they just change unique id (drive uploaded document) in URL (after ?id=) and than the documentis display in on a canvas. It's also SEO friendly and indexed by google. So what should be it's raw code?
Demo - Click Here | I want this One {Check Code by Inspect Tool}
Demo Website Image/Inspect code
I just want to use google drive for storage and call document on my website's pdf.js canvas for increase page view, user time, and display ads on PDF web pages like the demo that above.
Here are is the demo for PDF.JS showing PDF in the webpage
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf'; //Loaading the PDF from URL
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 0.8,
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
/**
* Get page info from document, resize canvas accordingly, and render page.
* #param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport({scale: scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function() {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
// Update page counters
document.getElementById('page_num').textContent = num;
}
/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
#canvas {
border: 1px solid black;
}
button{
border: none;
background: #000;
color: #fff;
margin: 10px;
padding: 10px;
}
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<h1>PDF.js Example</h1>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="canvas"></canvas>
For more details and documentation visit:
https://mozilla.github.io/pdf.js/getting_started/
Changed pdf URLs to see the result
Tested here:
https://codepen.io/max-makhrov/pen/JjpLxXP
Here're failed URLs:
https://drive.google.com/open?id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
https://drive.google.com/1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O/export?exportFormat=pdf&format=pdf
https://drive.google.com/export?id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
https://drive.google.com/uc?export=download&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O&exportFormat=pdf&format=pdf
https://drive.google.com/uc?export=download&format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
https://drive.google.com/uc?export?format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
https://docs.google.com/viewer?srcid=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O&pid=explorer&efh=false&a=v&chrome=false&embedded=true
https://drive.google.com/file/d/1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O/
https://drive.google.com/file/export?format=pdf&id=1MUgtKfMqpyTtTFt2hEff23Emcg14Cj4O
Here's a surprise: you may use a range from existing Google Sheet if it has an Access. This URL works:
https://docs.google.com/spreadsheets/d/1qNQ6iCMoBCQgJzBB63ymtBQ6BedXZFhjgZZKGItjeVA/export?exportFormat=pdf&format=pdf&size=1.87x1.386&portrait=true&scale=2&top_margin=0&bottom_margin=0&left_margin=0&right_margin=0&sheetnames=false&printtitle=false&horizontal_alignment=LEFT&gridlines=false&fmcmd=12&gid=0&r1=1&r2=7&c1=1&c2=4
I added a demo to load pdf with lazy load. We need to implement drive api to fetch the pdf from drive or it will give cross-origin error.
<!DOCTYPE html>
<html>
<head>
<title>PDF Demo for Qdev</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/pdfjs-dist#2.2.228/build/pdf.min.js"></script>
<style>
body {
margin: 0;
background-color: #dfdfdf; /* Grey background */
}
.center {
text-align: center; /* center pages */
}
</style>
</head>
<body>
<div id="pages" class="center"></div>
<script>
// download the pdf
var pdfTask = pdfjsLib.getDocument("https://atikur-rabbi.github.io/data/sample.pdf");
// parse the get params
var queryString = window.location.hash.split("#")[1];
// default params
var params = {pg: 1};
var pagen = 0;
// if get params are present
if (queryString) {
// update the default settings
params = Object.assign(params, parseParams(queryString));
}
// Load the pages div from the DOM
var pages = document.getElementById("pages");
// handle the pdf once loaded (asyncronous)
pdfTask.promise.then(function(pdf) {
// globalize pdf
window.pdf = pdf;
// load the first page
loadPage(pdf, parseInt(params.pg));
pagen++;
});
// stores the page number of the page currently in the viewport
var curpage = parseInt(params.pg) + pagen;
// every half a second, check for scroll updates
setInterval(function() {
// if we're within 200px of the bottom of the page
if (document.body.scrollHeight - (window.scrollY + window.innerHeight) < 200) {
if (window.pdf != undefined) {
// load 5 more pages
for (var i=0; i<5; i++) {
loadPage(pdf, parseInt(params.pg)+pagen);
pagen++;
}
}
}
// if the page in our viewport has changed, update the url
if (curpage != parseInt(params.pg) + parseInt(window.scrollY /
(document.body.scrollHeight / pagen))) {
curpage = parseInt(params.pg) + parseInt(window.scrollY /
(document.body.scrollHeight / pagen));
window.location.hash = "#pg=" + curpage;
}
}, 500);
// render `pg` from `pdf` and append it to the pages div
function loadPage(pdf, pg){
pdf.getPage(pg).then(function(page){
var scale = 1.7;
var viewport = page.getViewport({scale: scale});
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.id = "page-" + pg;
canvas.height += viewport.height;
canvas.width = viewport.width;
pages.appendChild(canvas);
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
}
// parses get params from a query string into an object
function parseParams(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
</script>
</body>
</html>

PDF.js get images of one page and display them as HTML

according to this: [Extract images from PDF file with JavaScript
I tried to filter the JPEG images from PDF. It works in the way, that I get the name of the images of one page in an array.
What I want to do: Display the images next to the PDF as HTML . The solution mentioned above doesn't work, I do not know, how to get the image itself and not just the name.
<script type="text/javascript" src="pdf.js"></script>
<script type="text/javascript">
PDFJS.workerSrc = "/path/to/pdf.worker.js";
</script>
<div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas" style="width: 500px;"></canvas>
<div id="images"></div>
<script type="text/javascript">
PDFJS.workerSrc = "pdf.worker.js";
</script>
<script src="js.js"></script>
js.js:
// URL of PDF document
var url = "test/pdf_one.pdf";
var pageNum = 11;
var pageCount = 0;
loadPage(pageNum);
function loadPage(number){
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
pageCount = pdf.numPages;
document.getElementById("page_num").innerHTML = "" + pageNum;
document.getElementById("page_count").innerHTML = "" + pageCount;
return pdf.getPage(number);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
getImages(page);
});
}
function getImages(page){
var test = [];
page.getOperatorList().then(function (ops) {
for (var i=0; i < ops.fnArray.length; i++) {
if (ops.fnArray[i] == PDFJS.OPS.paintJpegXObject) {
console.log(ops.argsArray[i][0]);
document.getElementById("images").innerHTML = "<img src='"+ops.argsArray[i][0]+".jpg'>";
test.push(ops.argsArray[i][0])
}
}
});
console.log(test);
if(pageNum === 13){
console.log("IMAGES");
console.log(test[0]);
document.getElementById("images").innerHTML = "<img src='"+test[0]+".jpg'>";
}
}
document.getElementById('prev').addEventListener('click', onPrevPage);
document.getElementById('next').addEventListener('click', onNextPage);
function onNextPage() {
if (pageNum >= pageCount) {
return;
}
pageNum++;
document.getElementById("page_num").innerHTML = "" + pageNum;
loadPage(pageNum);
}
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
document.getElementById("page_num").innerHTML = "" + pageNum;
loadPage(pageNum);
}

app.receivedEvent is not a function

I am building a phonegap application and I get the following error message when debugging.
Uncaught TypeError: app.receivedEvent is not a function(…)** on line 18 of my JS code (I point it out below).
To be honest I have read many guides on the deviceready but I just can't figure out how to properly use it for my phonegap build code.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- Include meta tag to ensure proper rendering and touch zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<!-- Include jQuery Mobile stylesheets -->
<link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css">
<link href='https://fonts.googleapis.com/css?family=Lobster|Anton|Patua+One' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/fact_page.css">
<title>One Direction Facts</title>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h1>One Direction - Fact of the Day</h1>
</div>
<div id="deviceready" data-role="main" class="ui-content">
<h2 id="todayh2" class="invisible"> Today's One Direction Fact:</h2>
<div id="quotebox" class="PulseEffect icon">
<div id="ShineDiv" class="shine"></div>
<div class="facebox fade icon">
<div id="ShineDiv2" class=""></div>
</div>
<p class="hidden" id="qotd"> Welcome to<br><strong>One Direction Facts.</strong><br><br>You will get a random fact each day.</p>
</div>
<a id="nextQ" class="" data-role="button" data-ajax="false">View Fact</a>
<div class="XPmeter animateXP" >
<span id="bar" style="width: 20%"></span>
<div id="medaldiv">
<img id="medal" src="images/medal3.svg"><p id="lvl">1</p>
</div>
</div>
</div>
<div data-role="footer">
<h1>New Features Coming Soon!</h1>
</div>
</div>
<!-- --------------------JS------------------------ -->
<script src="./js/jquery-1.11.3.min.js"></script>
<script src="./js/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" src="js/app_scripts.js"></script>
<script type="text/javascript" src="js/admob.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
Here is my JS:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
/*--error is here-->*/ app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent:
$("#nextQ").click(function(){
var tempd = new Date(); //Get today's date
//Checks if localstorage had 'DateOpened' already stored
// Note that by adding strings in there, we end up with a string instead of adding.
// Note the order: Year first, then month, then day.
// Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDate();
console.log("Today's date: " + str);
var localVal = localStorage.getItem('DateOpened');
console.log("Previous localVal: " + localVal);
if(localVal != null){
var difference = localVal.localeCompare(str);
}
console.log("localeCompare: " + difference);
//If stored date is older than this date do something:
if(localVal == null || difference < 0){
// If the localstorage doesn't exist, nothing happens
console.log("App will now run once for today.")
//Run the JS for the app (give new quote since it is a new day)
var Quotes = [];
var ID = [];
var Tag = [];
//Get quotes from JSON file
$.ajax({
url: './json/facts.json',
dataType: 'json',
type: 'get',
success: function(data){
console.log(data);
console.log("successfully imported the JSON file");
console.log(data.length); //Returns 64
totalQ = data.length;
for (i = 0; i < totalQ; i++){
ID[i] = data[i][0];
Tag[i] = data[i][1];
Quotes[i] = data[i][2];
}
console.log(Quotes.length);
}
})
.done(function(data){ //This waits for AJAX to be done before running
var Quote = new String;
var qnumber = 0;
var totalQ //The total number of available quotes to choose from
var CurrentImage = String;
totalQ = Quotes.length - 1;
console.log("TotalQ = " + totalQ);
//Get list of which facts have already been seen
var seen = JSON.parse(localStorage.getItem('seen'));
console.log("var seen = " + seen);
if (seen == null){
var seen = new Array(totalQ);
for (var i = 0; i < seen.length; ++i) {
seen[i] = false;
}
console.log("var seen = " + seen);
}
//Get a Quote
ChooseQuote(0,totalQ);
//Change the image depending on the quote
//replace the quote with a new one
$("#qotd:visible").hide();
$("#ShineDiv").addClass("shine");
$(".facebox").css("background-image",CurrentImage);
$(".facebox").css("opacity","1.0");
$("#qotd").html(Quote);
console.log("Image Changed");
increaseXP();
//================
function ChooseQuote(min,max){
//Choose 2 random numbers, one for quotes one for image
var RandomNum = Math.floor(Math.random()*(max-min+1)+min);
var ImageNum = Math.floor(Math.random()*(5-1+1)+1);
Quote = Quotes[RandomNum];
CurrentImage = "url(./images/FaceBoxes/" + Tag[RandomNum] + "/" + Tag[RandomNum] + ImageNum + ".png)";
if (seen[RandomNum] == true ) {
//Choose new quote
ChooseQuote(0,totalQ);
console.log("Has this fact been seen before? Answer: " + seen[RandomNum] );
var numOfTrue = 0;
for(var i=0; i<=totalQ; i++){
if(seen[i] === "true")
numOfTrue++;
}
if (numOfTrue = totalQ) {
localStorage.setItem('All_Facts_Seen:', true);
console.log("All the Facts have been seen. Resetting Facts.");
seen = new Array(totalQ); //Empty the seen Array
localStorage.setItem('seen', JSON.stringify(seen)); //Save the empty Array
}
}
else {
seen[RandomNum] = "true";
console.log("This fact has never been seen.")
}
console.log(Quote);
console.log(CurrentImage);
//Remeber which fact is displayed
localStorage.setItem('Curr_Fact', Quote);
localStorage.setItem('Curr_ImgUrl', CurrentImage);
localStorage.setItem('seen', JSON.stringify(seen));
}
//==================
//Save the current date in local storage
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fact tomorrow");
console.log("Current LocalStorage Date: " + str);
});
}
else {
//If it is still the same day, show the last fact & image
var Quote = localStorage.getItem('Curr_Fact');
var CurrentImage = localStorage.getItem('Curr_ImgUrl');
$("#qotd:visible").hide(); //Hide main quote
$("#ShineDiv2").addClass("shine");
if ($('h2').hasClass("invisible")){ //if heading is invisble show it, remove that class
$('h2').css('visibility','visible').hide().fadeIn('slow').removeClass("invisible");
}
$(".facebox").css("background-image",CurrentImage);
setTimeout( function() { //This is so that the first image and new image don't crossfade/stretch
$(".facebox").css("opacity","1.0");
}, 100);
$("#qotd").html(Quote); //Replace the main message with the actual quote
console.log("Showing the same fact as before. Wait until tomorrow to get a new fact.");
}
},
};
$(window).load(function() {
var headerh;
var footerh;
var pageh;
var hbtn_nextq;
headerh = $("div[data-role='header']").outerHeight();
footerh = $("div[data-role='footer']").outerHeight();
pageh = $(window).height();
console.log(headerh + " " + footerh + " " + pageh);
var difference = pageh - headerh - footerh;
$(".ui-content").css("height", difference);
var h1, h2, h3, h4 , h5;
h1 = $(".ui-content").outerHeight();
h2 = $(".ui-content>h2").outerHeight();
h3 = $("#quotebox").outerHeight(true);
h4 = $("#nextQ").outerHeight();
h5 = ((h1 - h2 - h3 - h4) /2) - 50;
console.log(h1);
console.log(h2);
console.log(h3);
console.log(h4);
console.log(h5);
var h5s = h5 + "px";
//$("#quotebox").css("margin-top",h5s);
$(".ui-content>h2").css("margin-top",h5s);
//$("#nextQ").css("margin-bottom",h5s);
//ShowXP();
//Make the quotebox flip over on click
$(".facebox, #ShineDiv").click(function(){
$("#quotebox").removeClass("PulseEffect")
$("#ShineDiv").removeClass("shine");
$(".facebox").css("opacity","0");
$("#qotd").fadeIn("slow", function(){});
});
ShowXP();
});
function increaseXP(){
//Get the lvl and xp from storage
var lvl = localStorage.getItem("lvl", lvl);
var XP = localStorage.getItem("XP", XP);
console.log("Old XP = " + XP + " Old Level = " + lvl);
lvl = parseInt(lvl);
XP = parseInt(XP);
//Increase XP
XP = XP + 25;
//Increase lvl
if (XP >= 100){
lvl = lvl + 1;
localStorage.setItem('XP',XP);
localStorage.setItem('lvl',lvl);
UpdateXP(XP);
setTimeout(function() {
ShowUP(lvl);
}, 200);
XP = XP - 100;
console.log("Current XP = " + XP + " Current Level = " + lvl);
UpdateXP(XP);
}
localStorage.setItem('XP',XP);
localStorage.setItem('lvl',lvl);
UpdateXP(XP);
}
function ShowXP(){
var XP = localStorage.getItem("XP");
var lvl = localStorage.getItem("lvl");
if (XP == null){
XP = 0;
localStorage.setItem("XP", XP);
}
if (lvl == null){
lvl = 1;
localStorage.setItem("lvl",lvl);
}
lvl = parseInt(lvl);
XP = parseInt(XP);
$("#lvl").text(lvl);
$(".XPmeter > span#bar").each(function() {
$(this)
.data("origWidth", XP)
.width(0)
.animate({
width: $(this).data("origWidth") + "%" // or + "%" if fluid
}, 1200);
});
}
function UpdateXP(XP){
$(".XPmeter > span#bar").each(function() {
$(this)
.animate({
width: XP + "%" // or + "%" if fluid
}, 1200);
});
}
function ShowUP(new_level){
$("#medal").animate({height: "100px" },600, function(){
$("#lvl").text(new_level);
$("#medal").animate({height: "50px" },600);
});
$(".XPmeter > span#bar").width("0");
}
//-------------------------------------------------------------//
// //
// This is the scirpt that will get the facts and display them //
// //
//-------------------------------------------------------------//
That's because your receivedEvent is not defined as a functions but as a property of the app object so it can't be called as a function.
You to change it from:
// Update DOM on a Received Event
receivedEvent:
to:
// Update DOM on a Received Event
receivedEvent: function(id) {

Trying to change an image using an array in JavaScript

<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
index=(0)
var traffic = ["Red","Rambo","Green","Yellow"]
function changeImage() {
var image = document.getElementById('Light');
if traffic[index] === "Red" {
image.src = "Rambo.jpg";
index= (index+1)
} else if traffic[index] === "Rambo" {
image.src = "Green.jpg";
index= (index+1)
} else if traffic[index] === "Green" {
image.src = "Yellow.jpg";
index= (index+1)
} else {
image.src = "Red.jpg";
index=0
}
}
</script>
</html>
</body>
this is my code I don't understand why when i click the button the image doesn't change the images are all .jpg files are all contained inside the same folders and all are the same size any ideas why is will not change the image i'm currently guessing it's something to do with the === or the fact i'm using words instead of numbers for them
Lots of things going wrong here:
Parenthese around the if statements
Closing body tag after closing html tag
document.getElementById does not get the same id as the img id
So, this will work, but perhaps checking the javascript and HTML syntax first might be a good start:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
var index = 0;
var traffic = ["Red","Rambo","Green","Yellow"];
var image = document.getElementById('myImage');
function changeImage() {
if (traffic[index] === "Red") {
image.src = "Rambo.jpg";
index++;
} else if (traffic[index] === "Rambo") {
image.src = "Green.jpg";
index++;
} else if (traffic[index] === "Green") {
image.src = "Yellow.jpg";
index++;
} else {
image.src = "Red.jpg";
index = 0;
}
}
</script>
</body>
</html>
There are few little mistakes in your code.
The id of your image is myImage, but you wrote var image = document.getElementById('Light'); which result on undefined.
As mentioned by PierreDuc, you missed parenthesis around if conditions.
Take a look at this example : https://jsfiddle.net/1wjn943x/
var images = [
"http://openphoto.net/thumbs2/volumes/mylenebressan/20120720/openphotonet_11.jpg",
"http://openphoto.net/thumbs2/volumes/sarabbit/20120322/openphotonet_DSCF5890.JPG",
"http://openphoto.net/thumbs2/volumes/Sarabbit/20120117/openphotonet_gerberadaisy3.jpg"
];
var index = 0;
var img = document.getElementById("myImage");
document.getElementById("button").addEventListener('click', function() {
// Next image.
index = (index + 1) % images.length;
// Setting `src`attribute of <img>.
img.src = images[index];
});
This is the easiest way to change the image.
Simply set the image source to be the next image in the array. You need to use the mod operator to loop from the end; back to the beginning.
Array - Index Pointer
var imageEl = document.getElementById('Light');
var index = 0;
var images = [
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
];
function changeImage() {
imageEl.src = images[index++ % images.length]; // Set and increment the image index.
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Map - Linked Pointer
var imageEl = document.getElementById('Light');
var currImage = '';
var images = {
red : {
src : "http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
next : 'rambo'
},
rambo : {
src : "http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
next : 'green'
},
green : {
src : "http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
next : 'yellow'
},
yellow : {
src : "http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow",
next : 'red'
}
};
function changeImage() {
(function(img) {
imageEl.src = img.src; // Set the image source to the current image.
currImage = img.next; // Set current image as the next image.
}(images[currImage || 'red']));
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Class - Circular Iterator
var CircularIterator = function(iterable) {
this.iterable = iterable || [];
this.index = 0;
this.get = function(index) {
return this.iterable[index] || this.next();
};
this.size = function() {
return this.iterable.length;
};
this.incr = function() {
return this.index = ((this.index + 1) % this.size());
};
this.next = function() {
return this.get(this.incr());
};
this.first = function() {
return this.get(0);
};
this.last = function() {
return this.get(this.size() - 1);
};
};
var imageEl = document.getElementById('Light');
var iterable = new CircularIterator([
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
]);
function changeImage() {
imageEl.src = iterable.next(); // Set and increment the image index.
}
imageEl.src = iterable.first(); // Set the current image to the first.
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>

Random image appear when website is loaded

I have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.
You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/
1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

Categories

Resources