For image upload in a cakephp project I used java-script.I added this js file in app\View\Layouts default.ctp
js code
document.querySelector('input[type=file]').addEventListener('change', function(event){
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
if (files[i].type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
var imageElement = document.createElement('div');
imageElement.classList.add('uploading');
imageElement.innerHTML = '<span class="progress"><span></span></span>';
var progressElement = imageElement.querySelector('span.progress span');
progressElement.style.width = 0;
document.querySelector('form div.photos').appendChild(imageElement);
var canvas = document.createElement('canvas'),
max_size = 1200,
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// Update progress
xhr.upload.addEventListener('progress', function(event) {
var percent = parseInt(event.loaded / event.total * 100);
progressElement.style.width = percent+'%';
}, false);
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
imageElement.classList.remove('uploading');
imageElement.classList.add('uploaded');
imageElement.style.backgroundImage = 'url('+xhr.responseText+')';
console.log('Image uploaded: '+xhr.responseText);
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
xhr.open('post', 'process.php', true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
event.target.value = '';
I have checked there are no problem.
now in add.ctp file I adder
<input type="file" multiple />
In output I am seeing the file type field.Now when I clicked on this field and upload a image then mojila bug given me a error.That is
document.querySelector(...) is null error
I have no idea about this error.In here why saying queryselector is null?
document.querySelector() behaves similarly to the jQuery.(document).ready() method. When the DOM is ready, the selector returns the object.
I would suggest you call all JS script bottom of the page.
To make sure that your DOM is ready you could add this to your JS file.
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.querySelector('input[type=file]')
.addEventListener('change', function(event){
...
}
});
This way you could call your js files from wherever you like. Please take a look to this superb answer to get further insight on these matters.
Also take a look at this other Google rule.
file.js
const heading1 = document.querySelector(".heading1");
console.log(heading1);
Solution 1
Use defer (best & recommended way):
<!DOCTYPE html>
<html lang="en">
<head>
<script src="./file.js" defer></script>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
</body>
</html>
Solution 2
Place your JavaScript in bottom before closing body tag
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
<script src="./file.js"></script>
</body>
</html>
I suggest writing your <script type="text/javascript" src="your js file"></script> in body, before the closing tag
There is now another "better" way to address this issue.
put your scripts in the head tag and add the defer attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script src="main.js" defer></script>
</head>
<body>
yoyoyo
</body>
</html>
you can read more about it here and here
TLDR (may be inaccurate and misleading so read the sources above!):
the defer attribute tells the browser to load the file but hold off its execution until the dom is ready, which is close to the behavior you implicitly get when you put the script tag at the bottom of the body tag, the difference being that in the old way you have to wait for the whole body tag to be parsed until you start downloading the script tag.
I ran into this issue where I was trying to do (slimmed down for simplicity):
<script type="text/javascript">
var svg = document.querySelector('svg');
console.log(svg);
</script>
on an element in the <body>:
<svg id="svg" viewBox="0 0 120 120" width="500px" height="500px"></svg>
Once I added jQuery and moved my lines inside of a $(document).ready(), it was fine:
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var svg = document.querySelector('svg');
console.log(svg);
});
</script>
Here's a quick fix. I was trying to effect some changes in my HTML page using DOM and was getting this error. The problem was I linked my Javascript file inside the head tag of the HTML page, when I changed that and linked it at the body just before the closing body tag, it worked!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Soft dog</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.4.1/dist/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link rel="stylesheet" href="landing.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=Cormorant+SC:wght#300&family=Edu+VIC+WA+NT+Beginner&display=swap"
rel="stylesheet">
</head>
<body>
<div class="container">
<h2 id="newBrand">Welcome to SOFTDOG</h2>
<p><em>property of soft 6</em></p>
<a id="ceo" href="home.html"><img src="softdogmerch1.jpg" alt="check network"></a>
<p id="enterstatement">Please<a href="home.html">
<P><span>ENTER HERE</span></P>
</a><span>to feed your eyes and fill your wardrobe</span>
</p>
<label for="emailinput">email:</label>
<input id="emailinput" type="email" name="useremail" placeholder="user#email.com" required>
<label for="passwordinput">password:</label>
<input id="passwordinput" type="password" name="userpassword" placeholder="" required>
<input id="clickme" type="submit" name="login" value="log in">
<input id="clickme" type="submit" name="signup" value="sign up">
</div>
<script src="landing.js"></script>
</body>
</html>
Related
i want to pass the url of the image that was selected by the user in my python function views.py because my python function will process the image that was selected by the user. this is my html command
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
and here is the function on my python
def predict():
img = cv2.imread('C:/Users/HABITUS/Desktop/arvin files/download.jpg') #the url of the image selected must be here!!
img = cv2.resize(img, (600, 600))
enhancer = Image.fromarray(img)
enhancer = ImageEnhance.Contrast(enhancer)
enhanced = enhancer.enhance(1.5)
enhancer1 = ImageEnhance.Brightness(enhanced).enhance(1.3)
convert = scipy.misc.fromimage(enhancer1)
imgM = cv2.medianBlur(convert, 5)
# blurring and smoothening
kernel = np.ones((5, 5), np.uint8)
erosion = cv2.erode(imgM, kernel, iterations=1)
dilation = cv2.dilate(erosion, kernel, iterations=1)
blur = cv2.GaussianBlur(convert, (15, 15), 10)
grayscaled = cv2.cvtColor(imgM, cv2.COLOR_BGR2GRAY)
retval2, threshold2 = cv2.threshold(grayscaled, 200, 1, cv2.THRESH_BINARY_INV)
gaus = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
retval2, otsu = cv2.threshold(grayscaled, 140, 250, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
backtorgb = cv2.cvtColor(threshold2, cv2.COLOR_GRAY2RGB)
mult = cv2.multiply(img, backtorgb)
edges = cv2.Canny(threshold2, 120, 50)
the image that was selected by the user must be in cv2.imread() how can i do that? any advice or help will be appreciated thanks
this is somewhat confusing.
you might want to start with reading
https://docs.djangoproject.com/en/2.0/topics/forms/
And here are two existing questions that should help you:
Very simple user input in django
Need a minimal Django file upload example
I'm trying to shrink an image based off of what I learned on the mobile app SoloLearn. Please help.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css"/>
</head>
<body>
<img id="image" src="myImage.jpg"/>
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.style.width = 50;
img.syle.height = 25;
};
</script>
</body>
</html>
Rather then using img.style just set the width and height values of the image.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css" />
</head>
<body>
<img id="image" src="http://www.placehold.it/150" />
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.width = 50;
img.height = 25;
};
</script>
</body>
</html>
The width and height styles aren't numbers, they need units as well, like px for pixels. So
function shrnk() {
img.style.width = '50px';
img.style.height = '25px';
}
The only time you can omit the units is when you're setting them to 0, since that's the same regardless of the units.
If you'd like to use the style property you need to set the unit of the number you're talking about (ie. "px").
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css" />
</head>
<body>
<img id="image" src="http://lorempixel.com/200/200" />
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.style.width = "50px";
img.style.height = "25px";
};
</script>
</body>
</html>
Welcome again,and again. I have a lot of errors,it's just joking with me.
The code is works here => https://jsfiddle.net/jh5tkfpp/ posted by a forum member (Sridhar). But in my local-webserver it's throwing TypeError: comp1GameTitle is null .
var cGamePic = new Array("https://c6.staticflickr.com/9/8804/28522899701_efbaa953a7_n.jpg", "https://c5.staticflickr.com/7/6003/6004770804_692aecf57c_b.jpg", "https://c5.staticflickr.com/7/6006/6004652276_87ba0278a9_b.jpg", "https://c7.staticflickr.com/7/6139/6007896022_c7ac652043_b.jpg");
var cGameName = new Array("beach", "cycle1", "cycle2", "cycle3");
var randomItemContainer1 = Math.floor(Math.random() * cGamePic.length); //container1
var randomItemContainer2 = Math.floor(Math.random() * cGamePic.length); //container2
var comp1GameTitle = document.querySelector("#container1 h1"); //Heading from main container
var comp1GameImage = document.querySelector("#container1 img"); //Image from main container
var comp2GameTitle = document.querySelector("#container2 h1"); //Heading from main container
var comp2GameImage = document.querySelector("#container2 img"); //Image from main container
comp1GameTitle.innerHTML = cGameName[randomItemContainer1];
comp1GameImage.src = cGamePic[randomItemContainer1]; //Random image
<!doctype html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Random_page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="rnd.js"></script>
</head>
<body>
<div id="container1" style="float:left; width:40%; margin:10px;">
<h1>Title</h1>
<img src="" width='100%' height='100%' />
</div>
<div id="container2" style="float:left; width:40%; margin: 10px;">
<h1>Title</h1>
<img src="" width='100%' height='100%' />
</div>
</body>
</html>
It works in jsfiddle since they are executed onload. But you have put scripts in the head. So when they are executed DOM is not ready there is no element with id container1. So you can make changes as following snippet
<body>
//Rest of code
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="rnd.js"></script>
</body>
else you can still keep rnd.js inside header tag but put all code in rnd.js inside a window.onload function
I want to change an image's src on click of a link. I got a javascript snippet and tried to integrate it but it doesn't work.Im
Here's my HTML:
<html>
<head>
<meta charset="utf-8">
<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="styles/script.js"></script>
<img id="bgimage" src="images/1.jpg"/>
<nav id="nav">A | B |
</nav>
</body>
</html>
Here is my script.js:
var imageId = document.getElementById("bgimage");
function changeImage() {
if (imageId.src == "images/1.jpg")
{
imageId.setAttribute("src","images/2.jpg");
}
else
{
imageId.setAttribute("Src","images/1.jpg");
}
}
This issue is occurring because the script appears in the html before the <img> element. Therefore, the code tries to find the img element, but it can't because the js code executes before the rest of the html is parsed. Correct it by putting the js include tag just before </body>:
<html>
<head>
<meta charset="utf-8">
<link href="styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<img id="bgimage" src="images/1.jpg"/>
<nav id="nav">A | B |
</nav>
<script src="styles/script.js"></script>
</body>
</html>
Or, you might want to use DOMContentLoaded to wait until the html has been parsed. Change the js to this, in that case:
var changeImage;
document.addEventListener('DOMContentLoaded',function(){
var imageId = document.getElementById("bgimage");
changeImage=function() {
if (imageId.src == "images/1.jpg")
{
imageId.setAttribute("src","images/2.jpg");
}
else
{
imageId.setAttribute("Src","images/1.jpg");
}
}
},false);
Or you could call document.getElementById() every time changeImage is called
You must place your script just before </body>, or run it at onload.
If not, you run
var imageId = document.getElementById("bgimage");
before loading the image to the DOM, so imageId is null.
Anyway, you could improve your function to
var images = ["images/1.jpg", "images/2.jpg" /*, ... */];
function changeImage() {
imageId.src = images[(images.indexOf(imageId.src)+1) % images.length];
}
I've got 3 files
file 1: index.html
<!DOCTYPE html>
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="bounce.js"></script>
<title>Bouncing ball</title>
</head>
<body>
<div id='ball'></div>
</body>
</html>
file 2: bounce.js
var ball = document.getElementById("ball");
var nx = 0;
var ny = 0;
setInterval(loop, 1000 / 30);
function loop() {
nx++;
ny++;
ball.style.left = nx;
ball.style.top = ny;
}
file 3: style.css
#ball {
position: absolute;
border-radius: 50px;
width: 50px;
height: 50px;
background: black;
}
i'm load the .css and the .js in the html file.
Now i'm trying to get te div "ball" and i want to do something with it. In this case, i want to let it bounce agains the borders of the browser. But the point is, i'm getting errors.
Uncaught TypeError: Cannot read property 'style' of null
The bonce.js can not get the elment ball. Why not? What am i doing wrong?
You are trying to get the element before it's loaded in the DOM. Do this:
<!DOCTYPE html>
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<title>Bouncing ball</title>
</head>
<body>
<div id='ball'></div>
<script type="text/javascript" src="bounce.js"></script>
</body>
</html>
It's a good practice to include all your JavaScript at the bottom, so it doesn't block the page while downloading. And it will make sure you don't have any errors like this.
That's because your code is executed before the DOM is ready. There is no element with this id at this time.
Put your code inside a onload callback :
window.onload = function(){
var ball = document.getElementById("ball");
var nx = 0;
var ny = 0;
setInterval(loop, 1000 / 30);
function loop() {
nx++;
ny++;
ball.style.left = nx;
ball.style.top = ny;
}
};
Move your script to the end of the page or wrap it in an onload event. You're executing it before the element has loaded.
<!DOCTYPE html>
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<title>Bouncing ball</title>
</head>
<body>
<div id='ball'></div>
<script type="text/javascript" src="bounce.js"></script>
</body>
</html>