Initial situation :
I have a JavaFX program where I put data into a MYSQL database, enter and save it.
In the JavaFX program, I have a PDF displayed via WebView using JavaScript. From the JavaFX programm i call the html to open the WebView
Problem:
If I display different data records, the respective PDF should be displayed.
Question:
How do I hand over the file path from JavaFX to JavaScript.
JavaFX Code to show the PDF
public void handleShowPDF(ActionEvent actionEvent) throws MalformedURLException {
try {
eWebView.setVisible(true);
webEngine = eWebView.getEngine();
webEngine.setJavaScriptEnabled(true);
URL url = this.getClass().getResource("/jScript/index.html");
webEngine.load(url.toString());
}
catch (Exception ex) {
System.err.print("error " + ex.getMessage());
ex.printStackTrace();
}
HTML Code for calling JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="style.css" />
<title>PDF Viewer</title>
</head>
<body>
<div class="top-bar">
<button class="btn" id="prev-page">
<i class="fas fa-arrow-circle-left"></i> Prev Page
</button>
<button class="btn" id="next-page">
Next Page <i class="fas fa-arrow-circle-right"></i>
</button>
<span class="page-info">
Page <span id="page-num"></span> of <span id="page-count"></span>
</span>
</div>
<canvas id="pdf-render"></canvas>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<script src="main.js"></script>
</body>
</html>
JavaScript Code
// How do I get the path value from JavaFX
const url = '../docs/pdf.pdf';
let pdfDoc = null,
pageNum = 1,
pageIsRendering = false,
pageNumIsPending = null;
const scale = 1.5,
canvas = document.querySelector('#pdf-render'),
ctx = canvas.getContext('2d');
// Render the page
const renderPage = num => {
pageIsRendering = true;
// Get page
pdfDoc.getPage(num).then(page => {
// Set scale
const viewport = page.getViewport({ scale });
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderCtx = {
canvasContext: ctx,
viewport
};
page.render(renderCtx).promise.then(() => {
pageIsRendering = false;
if (pageNumIsPending !== null) {
renderPage(pageNumIsPending);
pageNumIsPending = null;
}
});
// Output current page
document.querySelector('#page-num').textContent = num;
});
};
// Check for pages rendering
const queueRenderPage = num => {
if (pageIsRendering) {
pageNumIsPending = num;
} else {
renderPage(num);
}
};
// Show Prev Page
const showPrevPage = () => {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
};
// Show Next Page
const showNextPage = () => {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
};
// Get Document
pdfjsLib
.getDocument(url)
.promise.then(pdfDoc_ => {
pdfDoc = pdfDoc_;
console.log(pdfDoc);
document.querySelector('#page-count').textContent = pdfDoc.numPages;
renderPage(pageNum);
})
.catch(err => {
// Display error
const div = document.createElement('div');
div.className = 'error';
div.appendChild(document.createTextNode(err.message));
document.querySelector('body').insertBefore(div, canvas);
// Remove top bar
document.querySelector('.top-bar').style.display = 'none';
});
// Button Events
document.querySelector('#prev-page').addEventListener('click', showPrevPage);
document.querySelector('#next-page').addEventListener('click', showNextPage);
Related
I have searched through several posts regarding this same issue but none seem to resolve my problem. I am getting this 404 error in my console: index.css:1 GET http://localhost:5500/assets/css/assets/css/Battleship-Wallpaper.jpeg 404 (Not Found)
I have the image saved in .jpeg format inside of my CSS folder. I am attempting to link the relative path and set the background image like so: background-image: url('assets/css/Battleship-Wallpaper.jpeg');
I have tried moving the image into different file locations within my project, as well as linking the entire filepath, to no avail. The rest of my CSS is loading just fine, here is how I am linking the CSS to my HTML: <link rel="stylesheet" href="./assets/css/index.css">. My intuition tells me that this is a problem with the server. I did not write the code for it, but I have reviewed it and have not been able to find a culprit.
The following is a snippet of the relevant HTML/CSS/JS server code.
const http = require("http");
const { readFileSync } = require("fs");
const path = require("path");
// Create a server using `http`
const server = http.createServer((req, res) => {
console.log(`Incoming Request - Method: ${req.method} | URL: ${req.url}`);
// Process the body of the request
let reqBody = "";
req.on("data", (data) => {
reqBody += data;
});
// When the request is finished processing the entire body
req.on("end", () => {
// Parsing the body of the request
if (reqBody) {
req.body = reqBody
.split("&")
.map((keyValuePair) => keyValuePair.split("="))
.map(([key, value]) => [key, value.replace(/\+/g, " ")])
.map(([key, value]) => [key, decodeURIComponent(value)])
.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
}
// Home Page
if (req.method === "GET" && req.url === "/") {
const resBody = readFileSync("./index.html");
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.end(resBody);
return;
}
// Serving Static Assets
const ext = path.extname(req.url);
if (req.method === "GET" && ext) {
try {
const resBody = readFileSync('.' + req.url);
res.statusCode = 200;
if (ext === ".jpg" || ext === ".jpeg") {
res.setHeader("Content-Type", "image/jpeg");
} else if (ext === ".css") {
res.setHeader("Content-Type", "text/css");
} else if (ext === ".js") {
res.setHeader("Content-Type", "text/javascript");
}
res.end(resBody);
return;
} catch {
console.error(
"Cannot find asset",
path.basename(req.url),
"in assets folder"
);
}
}
// Page Not Found
res.statusCode = 404;
res.setHeader("Content-Type", "text/plain");
const resBody = "Page Not Found";
res.write(resBody);
res.end();
});
});
// Set the port to 5000
const port = 5000;
// Tell the port to listen for requests on localhost:5000
server.listen(port, () => console.log("Server is running on port", port));
body {
font-family: 'Orbitron', sans-serif;
background-image: url('./assets/css/Battleship-Wallpaper.jpeg');
background-size: cover;
display: table-cell;
vertical-align: middle;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Battleship</title>
<link rel="stylesheet" href="./assets/css/index.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght#500&display=swap" rel="stylesheet">
<script type="module" src="./assets/js/index.js"></script>
</head>
<body>
<center>
<h1 class="headers">Battleship</h1>
<h2 class="headers" id="results"></h2>
<button id="reset">Play Again</button>
<div id="gameBox"></div>
</center>
</body>
</html>
In case this has anything to do with my DOM functionality, here is the relevant JS:
import Board from "./board.js";
let board = new Board();
const grid = board.grid;
const gameBox = document.getElementById('gameBox');
const reset = document.getElementById('reset');
const checkPosition = (currButton, currButtonVal) => {
let currResults = document.getElementById('results');
if (!currButtonVal) currButton.style.backgroundColor = 'red';
if (currButtonVal) {
currButton.innerHTML = currButtonVal;
currButton.style.backgroundColor = 'green';
board.numRemaining--;
if (board.isGameOver()) {
currResults.innerText = 'You win!';
gameBox.style.display = 'none';
reset.style.display = 'block';
};
};
};
const populateBoard = (grid) => {
for (let row = 0; row < grid.length; row++) {
let currDiv = document.createElement('div');
currDiv.setAttribute('id', `row-${row}`)
currDiv.setAttribute('class', 'rows');
currDiv.style.display = 'flex';
gameBox.appendChild(currDiv);
for (let col = 0; col < grid.length; col++) {
const currButtonVal = board.makeHit(row, col);
let currButton = document.createElement('button');
currButton.setAttribute('id', `col-${col}`);
currButton.setAttribute('class', 'buttons');
currButton.addEventListener('click', e => {
if (board.isGameOver()) e.preventDefault();
checkPosition(currButton, currButtonVal);
});
currDiv.appendChild(currButton);
};
};
};
window.addEventListener("DOMContentLoaded", () => {
populateBoard(grid);
reset.addEventListener("click", () => {
window.location.reload(true);
});
});
Any insight would be greatly appreciated.
If i check your code i see 3 different pathes:
In your entry text you write:
one time css/assets/css...jpeg
and the other one is css/assets/...jpeg
and later on in the code i see it going one folder up with the dot
background-image: url('./assets/css/Battleship-Wallpaper.jpeg');
Can you double check if you have a simple typing error?
I'm a newbie in javascript and need your help.
I don't know what to do and how to do to make this working:
I have the following js and html code:
var slides = '';
var slideImg = slider.images;
var i;
for (var i=0; i<slider.images.length; i++) {
slides += '<div id="slide'+i+'" class="slideEl" ><img src="'+slider.images[i].src+'"><div class="container-images">'+slider.images[i].CTA.text+'</div></div>';
}
document.getElementById('slides').innerHTML = slides;
document.getElementById('slides').style.width = window.innerWidth * (slideImg.length) + 'px';
document.getElementById('slides').style.transitionDuration = slideImg[0].speed + 's';
document.getElementById('slides').style.left = 0;
var indexSlide = 0;
function moveSlide(params) {
var slideWidth = document.getElementsByClassName('slideEl')[0].offsetWidth;
document.getElementById('slides').style.transitionDuration = slideImg[0].speed + 's';
var element = document.getElementById('slides');
var rect = element.getBoundingClientRect();
var newPos = rect.left;
if(params == 'right' && indexSlide < slideImg.length -1){
newPos -= slideWidth;
indexSlide++;
} else if (params == 'left' && indexSlide > 0) {
newPos += slideWidth;
indexSlide--;
}
document.getElementById('slides').style.transitionDuration = slider.images[indexSlide].speed + 's';
document.getElementById('slides').style.left = newPos + 'px';
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JS exercise</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="media/favicon-32x32.png" />
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
</head>
<body>
<div id="slider">
<div id="slides" class="slides"></div>
<div class="container-slider">
<span id="arrowLeft" class="arrow" onclick="moveSlide('left')">〈</span>
<span id="arrowRight" class="arrow" onclick="moveSlide('right')">〉</span>
</div>
</div>
<footer>Copyright © 2019</footer>
<script language="javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/data.json"></script>
</body>
</html>
and besides that, I have another file called data.json:
[{
"autoplay" : "yes",
"transition" : "slide",
"images" :[
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://test.com",
"position" : "bottom-right"
}
},
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://test.com",
"position" : "bottom-right"
}
},
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://www.test.com",
"position" : "bottom-right"
}
}
]
}]
How can I get the slider var from json to javascript just to defined the length of the whole slider?
EDIT(from answer):
#Mrunmay Deswandikar, I've added this piece of code at the start of my script.js file:
var xhttp = new xmlhttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
}
};
xhttp.open("GET", "http://wip.2mo.ro/sandra/js-slider/js/data.json", true);
xhttp.send();
var slides = '';
var slideImg = slider.images;
.....
I got this error: Uncaught ReferenceError: xmlhttpRequest is not defined
at script.js:1
(anonymous) # script.js:1
What am I missing?
Many thanks,
Sandra
Script tags are not meant to be used to load json data. Use fetch instead.
fetch('js/data.json')
.then(res=>res.json())
.then(data=>{
const slider = data.shift();
/** rest of your code here */
})
.catch(err=>{
console.log(err.message);
});
Fetch by default uses promises, but if you prefer to use it with async/await (syntaxical sugar for Promises).
async function loadData(){
const res = await fetch('/js/data.json');
const data = await res.json();
const slider = data.shift();
/** rest of code here */
}
loadData().catch(err=>console.log(err);
To get the data from json, use Ajax request to load JSON file.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
}
};
xhttp.open("GET", "data.json", true);
xhttp.send();
This will get all the data of data.json file, into variable data.
If your data.json file is located at the same directory, else you can use releative path, but best way will be use server path, like,
xhttp.open("GET","https://yourwebsite/DIRECTORY/data.json",true);
What I want to achieve is that, when I click on a button, an overlay div containing the Dropzone.js form is created and displayed.
Here's the "normal" script I used before, and everything works fine.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css">
</head>
<body>
<h1>Upload your files</h1>
<form action="uploads" method="post" enctype="multipart/form-data" class="dropzone" id="my-dropzone">
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>
<script>
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: 1, // MB
maxFiles: 1,
acceptedFiles: ".jpg",
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
};
</script>
</body>
</html>
Here's the script that doesn't work:
$(document).ready(function () {
/**
* Promises to load the Dropzone.js files on CDNs
*/
function myAsyncFunction(type, url) {
return new Promise(function (resolve, reject) {
if (type === "js") {
var script = document.createElement("script");
script.src = url;
script.type = "text/javascript";
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
} else if (type === "css") {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
}
})
}
/**
* Overlay div
*/
var uploadDiv = function (__callback) {
var div = document.createElement('div');
div.setAttribute('id', 'dropzone-container');
document.body.appendChild(div);
var h1 = document.createElement('h1');
h1.textContent = "Upload file";
div.appendChild(h1);
var form = document.createElement('form');
form.setAttribute('action', 'uploads');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('class', 'dropzone');
form.setAttribute('id', 'my-dropzone');
div.appendChild(form);
__callback();
};
/**
* Does the job and call the Dropzone object
*/
var upload = function () {
// Get data-options
var options = JSON.parse(this.dataset.options);
// Create HTML
uploadDiv(function () {
myAsyncFunction('css', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css')
.then(
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js')
.then(
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: options.maxFilesize, // MB
maxFiles: options.maxFiles,
acceptedFiles: options.acceptedFiles,
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
}
)
)
});
}
/**
* Attach EventListener.
* #type {HTMLCollectionOf<Element>}
*/
var btnUpload = document.getElementsByClassName('mb-upload');
for (var i=0; i<btnUpload.length; i++) {
btnUpload[i].addEventListener("click", upload);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<input type="button" class="form-control btn btn-warning mb-upload" data-options='{"maxFilesize":1,"maxFiles":1,"acceptedFiles":".jpeg,.jpg,.png,.gif"}' id="author_avatar" value="Upload...">
</body>
</html>
As you can see, the div is created and the Dropzone.js files are loaded, but the Dropzone form doesn't work as in the previous snippet.
Where am I wrong?
You had a syntax error,
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js').then(()=>{
//resolve function
})
$(document).ready(function () {
/**
* Promises to load the Dropzone.js files on CDNs
*/
function myAsyncFunction(type, url) {
return new Promise(function (resolve, reject) {
if (type === "js") {
var script = document.createElement("script");
script.src = url;
script.type = "text/javascript";
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
} else if (type === "css") {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
link.onload = resolve;
link.onerror = reject;
document.head.appendChild(link);
}
})
}
/**
* Overlay div
*/
var uploadDiv = function (__callback) {
var div = document.createElement('div');
div.setAttribute('id', 'dropzone-container');
document.body.appendChild(div);
var h1 = document.createElement('h1');
h1.textContent = "Upload file";
div.appendChild(h1);
var form = document.createElement('form');
form.setAttribute('action', 'uploads');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('class', 'dropzone');
form.setAttribute('id', 'my-dropzone');
div.appendChild(form);
__callback();
};
/**
* Does the job and call the Dropzone object
*/
var upload = function () {
// Get data-options
var options = JSON.parse(this.dataset.options);
// Create HTML
uploadDiv(function () {
myAsyncFunction('css', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css')
.then(
myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js')
.then(()=>{
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: options.maxFilesize, // MB
maxFiles: options.maxFiles,
acceptedFiles: options.acceptedFiles,
dictDefaultMessage: "Either drag your files or click",
addRemoveLinks: true
}
})
)
});
}
/**
* Attach EventListener.
* #type {HTMLCollectionOf<Element>}
*/
var btnUpload = document.getElementsByClassName('mb-upload');
for (var i=0; i<btnUpload.length; i++) {
btnUpload[i].addEventListener("click", upload);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<input type="button" class="form-control btn btn-warning mb-upload" data-options='{"maxFilesize":1,"maxFiles":1,"acceptedFiles":".jpeg,.jpg,.png,.gif"}' id="author_avatar" value="Upload...">
</body>
</html>
Pls I urge for assistance on how to upload video captured with phonegap android app. I could upload captured video, but I want the user of the app to watch the captured video before uploading it. That is where I'm having problem.
The code I am using is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/jquery.mobile-1.2.0.min.css" />
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/jquery.mobile-1.2.0.min.js"></script>
<script src="js/modernizr-latest.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#takeVideo").addEventListener("touchend", function() {
alert("Take video");
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 1, duration: 10});
}, false);
}
function captureError(e) {
console.log("capture error: "+JSON.stringify(e));
}
function captureSuccess(s) {
console.log("Success");
console.dir(s[0]);
var v = "<video controls='controls'>";
v += "<source src='" + s[0].fullPath + "' type='video/mp4'>";
v += "</video>";
document.querySelector("#videoArea").innerHTML = v;
}
function uploadFile(s) {
// Get URI of picture to upload
var img = document.getElementById('videoArea');
var mediaFile = img;
alert(mediaFile);
if (!mediaFile || (img.style.display == "none")) {
alert("Take picture or select picture from library first.");
return;
}
var ft = new FileTransfer(),
path = mediaFile.substr(mediaFile.lastIndexOf('/')+1),
name = mediaFile.name;
var options = new FileUploadOptions();
options.mimeType = "document";
options.fileName = name;
options.chunkedMode = true;
options.params = params;
ft.upload(path,
"http://www.example.com/folder/upload.php",
function(result) {
alert('Upload success: ' + result.responseCode);
alert(result.bytesSent + ' bytes sent');
},
function(error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
}
</script>
</head>
<body>
<button id="takeVideo">Take Video</button><br>
<b>Status:</b> <span id="camera_status"></span><br>
<div id="videoArea"></div>
<button type="submit" onclick="uploadFile();">Submit</button>
</body>
</html>
Pls I count on your assistance to solve this challenge. I do not know how to reference "video" tagname nor extract image path from the videoArea id of the div.
I am using fileReader for checking if a profile picture uploaded matches with my conditions. However, i don't have always the same result. Can you help me to fix that bug ?
Here my htlm code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File API</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
</div>
<script src="images.js"></script>
</body>
</html>
Here my javascript/fileReader (images.js) code:
window.onload = function()
{
var width=0;
var height=0;
var exten= false;
var size = false;
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e)
{
var file = fileInput.files[0];
var imageType = /image.png/;
if (file.type.match(imageType))
{
exten = true;
var reader = new FileReader();
reader.onload = function(e)
{
var img = new Image();
img.src = reader.result;
img.onload = function()
{
width=this.width;
height=this.height;
}
}
reader.readAsDataURL(file);
}
else
{
exten= false;
}
if(width == 50 && height ==50)
{
size = true;
}
else
{
size = false;
}
//Here, we check that the image matches with png and 50*50px
if(size && exten)
{
alert('Your image is ok.');
}
else
{
if(!size && !exten)
{
alert('Image needs to be 50*50px and in png');
}
else
{
if(!size && exten)
{
alert('Image needs to be 50*50px');
}
else
{
if(size && !exten)
{
alert('Image needs to be in png');
}
}
}
}
});
}
Thank you for your help
You've to wait the execution of the img.onload event before checking width and height.
The code that's outside that event handler and that uses those properties should be moved inside it.