show image and title , when button click in JavaScript - javascript

I want to show an image and a title when I click the button. I created a form to do it. It's only working to show "Title". Image is not showing. Here is the my code, please help me.
function showImage()
{
document.getElementById('showTitle').innerHTML=document.getElementById('imgTitle').value;
document.getElementById('showImage').innerHTML=document.getElementById('imagP').value;
}
<!-- Input Area-->
<input type="text" id="imgTitle"/>
<input type="file" id="imagP"/>
<button onclick="showImage()" >Show Image</button>
<!-- Show Image & Title-->
<p id="showTitle"></p>
<img src="" id="showImage">
<!-- JavaScript Code-->

You need to use FileReader to read the uploaded file.
function showImage() {
document.getElementById('showTitle').innerHTML=document.getElementById('imgTitle').value;
var preview = document.querySelector('#showImage');
var file = document.querySelector('#imagP').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
<input type="text" id="imgTitle"/>
<input type="file" id="imagP"/>
<button onclick="showImage()" >Show Image</button>
<!-- Show Image & Title-->
<p id="showTitle"></p>
<img src="" id="showImage">

here is we use fileChange function on each time you change file.
and add style of display none to img tag where we want to show image, so we can show/hide image on Show Image button click.
let file = null;
function showImage() {
document.getElementById('showTitle').innerHTML = document.getElementById('imgTitle').value;
const showImage = document?.getElementById('showImage');
showImage.style?.display = 'block';
showImage.src = window?.URL?.createObjectURL(file);
}
const fileChange = (fileObj) => {
document.getElementById('showTitle').innerHTML = '';
const showImage = document.getElementById('showImage');
showImage.style.display = 'none';
file = fileObj.target.files[0]
}
<!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.0">
<title>Document</title>
<style>
#editable {
width: 400px;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<input type="text" id="imgTitle" />
<input type="file" id="imagP" onchange="fileChange(event)" />
<button onclick="showImage()">Show Image</button>
<!-- Show Image & Title-->
<p id="showTitle"></p>
<img src="" id="showImage" style="display:none">
</body>
</html>

Simplest way to achieve it as below
function showImage()
{
document.getElementById('showTitle').innerHTML=document.getElementById('imgTitle').value;
if(document.getElementById('imagP').files[0] != null) {
document.getElementById('showImage').src=URL.createObjectURL(document.getElementById('imagP').files[0]);
} else {
alert("please select the image")
}
}
<input type="text" id="imgTitle"/>
<input type="file" id="imagP"/>
<button onclick="showImage()" >Show Image</button>
<!-- Show Image & Title-->
<p id="showTitle"></p>
<img src="" id="showImage">

Related

stuck appending image to dom

I am doing my first coding project and creating a meme generator with vanilla js and am stuck appending the inputted information as an image with text to the dom. here is what i have so far...can an image be inside the brackets for the function? i'm just stuck and would appreciate any input
<!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.0">
<title>Document</title>
</head>
<style>
h1 {text-align: center;}
h2 {text-align: center;}
p {text-align: center;}
div {text-align: center;}
</style>
<body>
<h1>DANK MEME MAKER THINGY</h1>
<form id="memeform">
<p><h2>Top Text: <input id="topText" type="text" name="top"></h2>
<h2></he>Bottom Text: <input id="bottomText" type="text" name="bottom"></h2>
<h2>Image Link: <input id="imageLink" type="url" name="image"></h2>
<div style="text-align:center">
<input id="Create Meme!" type="submit" value="Create Meme!">
</div>
<div class="container">
<img src="" alt="Snow" style="width:100%;">
<div class="bottom-left">Bottom Left</div>
<div class="top-left">Top Left</div>
<div class="top-right">Top Right</div>
<div class="bottom-right">Bottom Right</div>
<div class="centered">Centered</div>
</div>
</p>
</form>
<script src="memeproject.js"></script>
</body>
</html>
JS:
const form = document.querySelector("#memeform");
const topInput= document.querySelector('input[name="top"]');
const bottomInput= document.querySelector('input[name="bottom"]');
const imageInput= document.querySelector('input[name="image"]');
form.addEventListener('submit', function(evt){
evt.preventDefault();
console.log(topInput.value, bottomInput.value, imageInput.value);
});
function makeMeme(text,text,image){
const meme= document.createElement('img');
meme.innertext= text;
}
I found this code and it seems like it might be part of the answer you are looking for. You can upload a file from your computer so it displays on the web page.
var loadFile = function(event) {
var image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
<input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)">
<label for="file" style="cursor: pointer;">Upload Image</label>
<img id="output" width="200" />
Now you need to find a way of generating the HTML to put the top and bottom input fields supplied by the user above and below the image.
The code here works by adding an event handler (ie. a function which in this case is assigned to a variable called loadFile) to the file input element so that when that element detects a change it fires the event handler. The event handler uses the event object. I did not know it before but clearly event.target.files is an array of files paths and so event.target.files[0] is the path to the file that the user selected. I hope that helps and also hope it is correct.

How to generate a PDF from webpages the contain SVG elements?

In the following files I have an SVG image of squares and the pile of 4 squares on the left can be highlighted. If you click on the top square, the squares from 1 to 4 will be filled green. If you clicked on the square number 3, the squares from 1 to 3 will be filled green. If you clicked the square number 2, the squares 1 and 2 will filled green and if you clicked the square number 1 it will be filled green. I want to that after the user highlights what he/she needs from the left pile of squares and opens the notes form and writes some notes then click generate PDF and enters his/her email in the form that opens and then clicks generate, a PDF is generated which has an image exactly the same as on the webpage with the highlighting that the user did and the notes that the user entered and this PDF would be sent to the user through his/her email.
My PHP code:
<?php
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<!-- Font Awesome icons (free version)-->
<script src="https://use.fontawesome.com/releases/v5.15.1/js/all.js" crossorigin="anonymous"></script>
<!-- Google fonts-->
<link href="https://fonts.googleapis.com/css?family=Merriweather+Sans:400,700" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic" rel="stylesheet" type="text/css" />
<!-- Third party plugin CSS-->
<link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet" />
<!-- Core theme CSS (includes Bootstrap)-->
<link href="style.css" rel="stylesheet" />
</head>
<body id="page-top">
<section class="text-center">
<svg id="mainImage" width="564" height="409" onclick="handleSVGClick(event)">
<image
href="https://media.geeksforgeeks.org/wp-content/uploads/unique-rectangles-formed-using-n-unit-squares.png"
width="564"
height="409"
/>
<polygon id="B1_1" title="1" points="21,385 24,309 100,309 101,385" />
<polygon id="B1_2" title="2" points="102,305 23,304 23,228 101,227" />
<polygon id="B1_3" title="3" points="103,225 26,228 25,149 99,151" />
<polygon id="B1_4" title="4" points="103,147 102,65 25,70 23,147" />
</svg>
<button type="button" class="btn " style="background-color: rgb(64,120,43);" onclick="openNotes()">Open Notes</button>
<!-- <form method="POST" >
<input type="submit" class="button btn-primary" value ="generate" name="send"/>
</form>-->
<button type="button" class="btn " style="background-color: rgb(64,120,43);" onclick="openEmailForm()">Generate PDF</button>
<div class="form-popup" id="noteForm" style="top: 300px; left:1rem">
<div class="form-container text-justify" >
<header>
<h1 style="color:green"><strong>Notes</strong></h1>
</header>
<textarea class="action" id = "ActionBody" maxlength="2000" placeholder="Write your notes here" style="resize: none;" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
<br>
<button type="button" class="btn " style="background-color: rgb(64,120,43);" onclick="closeNotes()"> Close Notes</button>
</div>
</div>
<div class="form-popup" id="emailForm" style="top: 300px; left:8rem">
<div class="form-container text-justify" >
<header>
<h1 style="color:green"><strong>Email</strong></h1>
</header>
<label>please enter your email:</label>
<input type="text"></input>
<br>
<button type="button" class="btn " style="background-color: rgb(64,120,43);" > generate</button>
</div>
</div>
</section>
<!-- Bootstrap core JS-->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- Third party plugin JS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script>
<!-- Core theme JS-->
<script src="script.js"></script>
<script type="text/javascript" src="mapper.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://smtpjs.com/v3/smtp.js"> </script>
</body>
</html>
This is my JavaScript code:
function highlight(Num)
{
console.log("entered notes",Num);
notesTaken = Num;
console.log("notes",notesTaken);
for(var i =0; i<4;i++)
{
if(i<Num)
{
document.querySelectorAll("[id^='B1']")[i].style.fill="green";
document.querySelectorAll("[id^='B1']")[i].style.stroke="green";
}
else{
document.querySelectorAll("[id^='B1']")[i].style.fill="transparent";
document.querySelectorAll("[id^='B1']")[i].style.stroke="#E2E4E5";
}
}
//e.preventDefault();
}
function handleSVGClick(event) {
/*if (event.target.tagName === "polygon") {
console.log("entered");
event.target.style.fill = `hsl(${Math.random() * 360}, 90%, 60%)`;
console.log(filling);
//session['filling'] = filling;
// $.session.set("filling", filling);
//$.post("trial.php", {filling:filling});
document.cookie = "filling="+filling;
}*/
console.log("entered");
var idPolygon = event.target.id;
console.log(idPolygon);
var type = idPolygon.substring(0,2);
var Num = parseInt(idPolygon.slice(3),10);
console.log(Num);
if(type == "B1")
{
highlight(Num);
}
}
var filling = 8;
function openNotes() {
document.getElementById("noteForm").style.display = "block";
}
function closeNotes() {
document.getElementById("noteForm").style.display = "none";
}
function openEmailForm() {
document.getElementById("emailForm").style.display = "block";
document.getElementById("noteForm").style.display = "none";
}
function closeEmailForm() {
document.getElementById("emailForm").style.display = "none";
}
This is my CSS code:
polygon {
stroke-width: 2px;
stroke: #333;
fill: transparent;
}
.text-center {
text-align: center !important;
}
.hoverApply:hover{
fill:lightgray;
}
polygon {
stroke-width: 1px;
/*stroke: #333;*/
fill: transparent;
/*stroke-dasharray: 5;*/
stroke: #E2E4E5;
}
.form-popup {
display: none;
position: absolute;
border: 3px solid #54504A;
z-index: 9;
background-color: white;
max-width: 70%;
}
I tried a lot of things (like Dompdf and HTML2Canvas) and have been searching on how to do it for weeks and didn't reach a solution. I also checked those links but weren't helpful:
PHP Library to Convert HTML containg SVGs to PDF
Dompdf not generating PDF properly from SVG
Export SVG elements to PDF?
Convert SVG to PDF
How can we generate PDF/A or PDF from HTML (contains SVGs) using iText7?
Generate PDF from HTML and SVG
I'm trying to print a webpage containing JavaScript charts but the converted document contains everything Except those charts
Generating a PDF from a Tomcat-served webpage
wkhtmltopdf to HTML

Change only image orientation keeping other head as is

Is it possible to preserve other metadata by only changing orientation?
I am using https://github.com/blueimp/JavaScript-Load-Image
I have created following jsbin where when I replace head, it is losing orientation. Is there a way to fix this?
https://jsbin.com/cemeqeniru/2/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.jsdelivr.net/npm/exifr/dist/lite.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-load-image/5.14.0/load-image.all.min.js" integrity="sha512-HZg0q8NV+VTxnU6hdkK0rL+fSmTGCbXZ3mHjqCCi87St5QRdvXENfRxkMK692inskRsCPee07d7VwcKNWaByCQ==" crossorigin="anonymous"></script>
<script>
function onCameraCapture(file) {
document.getElementById('original').src = window.URL.createObjectURL(file);
loadImage(
file,
function (img, data) {
if (data.imageHead) {
img.toBlob(function (blob) {
loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
document.getElementById('converted').src = window.URL.createObjectURL(newBlob);
// do something with the new Blob object
})
}, 'image/jpeg')
}
},
{ meta: true, canvas: true, orientation: 1 }
);
}
</script>
</head>
<body>
File
<input type="file" accept="image/*" capture="camera" onchange="onCameraCapture(this.files[0])">
<br>
<br>
Take Photo
<input type="file" accept="image/*" capture="camera" onchange="onCameraCapture(this.files[0])">
<br>
<br>
Original
<img id="original" src="" width="100" height="100">
<br>
Converted
<img id="converted" src="" width="100" height="100">
</body>
</html>
LoadImage provides method to change only particular value.
loadImage.writeExifData(data.imageHead, data, 'Orientation', 1);

How to use the images taken from user using input tag HTML?

I have used <input type='file'> in which the user will place any image. Then i want to use that image as the background of the page. Is it possible to do that using just HTML , CSS , JAVASCRIPT ?
Basically my idea is to create a black and white image converter, i will take the picture from user input and then i will use filter: grayscale() property to convert that to black and white. Please help me.. My code is as following-
*{
margin: 0;
padding: 0;
}
/*Code for the image entered by user --
.image{
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 400px;
height: 400px;
background: url(); (set the image taken from user input)
filter: grayscale(100%);
}
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<h1>Black and White Image Converter</h1>
<label for="user-input">Attach the the image you want to convert : </label>
<input type="file" name="user-input" id="user-input" placeholder="Attach any image.."><!--Use this image-->
<div class="image"><!--I want to display that image as background of this div-->
</body>
</html>
Any help is appreciated..
I think I've got your code working:
first we load the input image input.files[0] into the browser (here I use file_reader). Then once the image loads, we set your effects, then the style.background of the <div> with id="background" to the url of the newly loaded image.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<h1>Black and White Image Converter</h1>
<label for="user-input">Attach the the image you want to convert : </label>
<input type="file" name="user-input" id="user-input" placeholder="Attach any image.." onchange="myFunction()"><!--Use this image-->
<div class="image" id="background"/><!--I want to display that image as background of this div-->
<script>
function myFunction() { //runs when file input is changed
var input = document.getElementById("user-input");
var file_reader;
if (input.files && input.files[0]) { //only if there is one file in the input
file_reader = new FileReader();
file_reader.onload = function(e) {
document.getElementById("background").style = "position: relative; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 400px; height: 400px;filter: grayscale(100%);"
document.getElementById("background").style.backgroundImage = "url('"+ e.target.result +"')";
console.log(e.target.src);
}
file_reader.readAsDataURL(input.files[0]);
}
}
</script>
</body>
</html>
function changeImage(input) {
var file_reader;
if (input.files && input.files[0]) {
file_reader = new FileReader();
file_reader.onload = function(e) {
document.getElementById("image").setAttribute('src', e.target.result);
}
file_reader.readAsDataURL(input.files[0]);
}
}
<input type="file" name="user-input" id="user-input" placeholder="Attach any image.." onchange="changeImage()" /><!--Use this image-->
<img id="image" />
Try this it may help!
HTML
<input type="file" name="user-input" id="user-input" placeholder="Attach any image..">
<button onclick="conversionFunction()">Convert to Black & White</button>
<div class="image" id="bgImg">
CSS
.image{
height: 400px;
width: 400px;
background-size: contain;
filter: grayscale();
background-repeat: no-repeat;
}
JavaScript
var btn = document.querySelector("#user-input");
function conversionFunction(){
var file_reader;
if (btn.files && btn.files[0]) {
file_reader = new FileReader();
file_reader.onload = function(e) {
document.querySelector("#bgImg").style.backgroundImage=`url(${e.target.result})`;
}
file_reader.readAsDataURL(btn.files[0]);
}
}
You can also see the working at following link https://jsfiddle.net/db0w9vfj/12/
I hope this will resolve your question.

How to make image to behave like file input?

When the default photo is clicked it should make a user to select a file from his computer other than making an input type = "file" that makes the user to first click on browse button than select a file. A user should directly click on default photo and a file selection window should appear.
<html lang = "en">
<head>
<title>
Profile Click
</title>
<style>
#file{
display: none;
}
</style>
</head>
<body>
<script>
function pro1(){
document.prolis.getElementById("image") = document.prolis.getElementById("file");
}
</script>
<form name = "prolis">
<img src = "index.jpg" id = "image" onclick = "pro1()";>
<input type = "file" id = "file">
</body>
</html>
Mozilla Firefox console shows "TypeError: document.prolis.getElementById is not a function".
How should I make this function work?
This is my default image:
To make the image behave like an input file element, you can just call the input file .click() method when you click on the img.
This is how should be your code:
function pro1(){
document.getElementById("file").click();
}
Demo:
<html lang = "en">
<head>
<title>
Profile Click
</title>
<style>
#file{
display: none;
}
</style>
</head>
<body>
<script>
function pro1(){
document.getElementById("file").click();
}
</script>
<form name = "prolis">
<img src = "index.jpg" id = "image" onclick = "pro1()";>
<input type = "file" id = "file">
</body>
</html>
Note:
You just need to use document.getElementById("file") to access an element by its id.
if you want to select element by id you should do it like this:
document.getElementById('element_id')
If you want to select form element you should do it like this:
document.form_name.element_id
Create a click event for #file in your function
function pro1(e){
e.preventDefault();
document.getElementById('file')[0].click();
});
}
You can replace image automatically with newly selected image.
<div class="image-upload">
<label for="file-input">
<img id="previewImg" src="https://icon-library.net/images/upload-photo-icon/upload-photo-icon-21.jpg" style="width: 100px; height: 100px;" />
</label>
<input id="file-input" type="file" onchange="previewFile(this);" style="display: none;" />
</div>
<script>
function previewFile(input){
var file = $("input[type=file]").get(0).files[0];
if(file){
var reader = new FileReader();
reader.onload = function(){
$("#previewImg").attr("src", reader.result);
}
reader.readAsDataURL(file);
}
}
</script>

Categories