stuck appending image to dom - javascript

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.

Related

I can't add a close tag to a list element in javascript

I created a To-do List, but I can't add a close tag to a list element in js. When I add the marked 5 lines of code in js my code doesn't work and I can't add a new list. Can you help me? Why it doesn't work, I didn't understand. I'm missing something..
I created a To-do List, but I can't add a close tag to a list element in js. When I add the marked 5 lines of code in js my code doesn't work and I can't add a new list. Can you help me? Why it doesn't work, I didn't understand. I'm missing something..
let form = document.querySelector('#form');
let reset = document.querySelector('#reset');
let myList = document.querySelector('#myList');
let text = document.querySelector('#text');
let submit = document.querySelector('#submit');
submit.addEventListener('click', function(e) {
e.preventDefault();
let liDOM = document.createElement('li')
liDOM.className = 'list-group-item'
liDOM.innerHTML = `${text.value[0].toUpperCase()}${text.value.slice(1)}`;
myList.appendChild(liDOM);
// If I add this 5 code lines, it doesn't work. WHY?
var span = document.createElement('span');
var text = document.createElement('\u00D7');
span.className = 'close';
span.appendChild(text);
liDOM.appendChild(span);
});
myList.addEventListener('click', function(item) {
if (item.target.tagName = 'li') {
item.target.classList.toggle('checked');
}
})
let counter = 0;
function myFunction() {
while (counter < myList.childElementCount) {
myList.removeChild(myList.firstChild);
}
}
ul li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
<!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>To Do List</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="index.css">
</head>
<body>
<form id="form">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6 col-md-8 mt-5">
<div class="card">
<div class="card-body">
<div class="input-group">
<input class="form-control" type="text" id="text" placeholder="What will you do today?">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit" id="submit">Ekle</button>
<button onclick="myFunction()" type="submit" id="reset" class="btn btn-outline-secondary">Sıfırla</button>
</div>
</div>
</div>
</div>
<div class="card mt-3">
<div class="card-header">My List</div>
<ul id="myList" class="list-group list-group-flush">
</ul>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
First of all good job, this was in nearly working condition and looks great.
There seemed to be a few minor problems with the implementation.
First, it is unusual/counterintuitive to have 2 different buttons each with type submit.
I would assume only first one should have type='submit'. The second one for presumably clearing the input should be type='button'. I also think they should have different styles to help warn the user that they have very different functionality.
Also, since the button has a submit functionality you don't need to also add an onclick functionality. It is very good to have an on submit functionality on the form and the single button with type='submit' as this allows the enter key to add a ToDo item.
Finally, the main focus of your problem was just that the text variable was already defined and you can't create an Element with the type × that is not an HTML type. See all the HTML elements on Mozilla Development search your favorite Search Engine for MDN Mozilla and within that search HTML for a list of current Legal HTML elements. It is very unlikely that an element will not be a word or abbreviation of some kind so that immediately tipped me off that: × was not an element tag that you can create they're more like (div, span, script, p, b, i). I think you meant for that to be the content of another span element that you wanted to create. Once you solved those 2 issues your code works!
I would just recommend that you append the × directly into the text because that's unfortunately the only element that doesn't fit. If not maybe you're going for a flex-box justify-content: space-between type thing where the × should always be on the right and the TODO on the left.
In that case you want the resulting HTML to be like:
<div style='display: flex; justify-content: space-between; align-items: center'>
<div>To Do text... I need to do stuff</div>
<button onclick='toggleComplete(12)'>×</button>
</div>
Keep in mind that for accessibility all clickable elements should really be buttons. If you need yo can cut back on the styling of this button and create a non-button-button class that resets all button specific styles to help you make it still look exactly how you want but work with screen readers.
let form = document.querySelector('#form');
let reset = document.querySelector('#reset');
let myList = document.querySelector('#myList');
let text = document.querySelector('#text');
let submit = document.querySelector('#submit');
submit.addEventListener('click', function(e) {
e.preventDefault();
let liDOM = document.createElement('li')
liDOM.className = 'list-group-item'
liDOM.innerText = `${text.value[0].toUpperCase()}${text.value.slice(1)}`;
myList.appendChild(liDOM);
// This was not working before because `text`
// was already defined above as `#text`
var newSpan = document.createElement('span');
// NOTE: for accessibility this must be a button.
const closer = document.createElement('span');
// this is probably what you meant to do... but
// note this needs some CSS love and the x itself doesn't work if you click
// on it so maybe just add it to the inner text instead:
// liDOM.innerText = `${text.value[0].toUpperCase()}${text.value.slice(1)} ×`;
closer.innerText = '×'
// perhaps add a special class here that gives it a red color
// perhaps only add the event listener to this button
newSpan.className = 'close';
newSpan.appendChild(closer);
liDOM.appendChild(newSpan);
});
myList.addEventListener('click', function(item) {
if (item.target.tagName = 'li') {
item.target.classList.toggle('checked');
}
})
let counter = 0;
function myFunction() {
while (counter < myList.childElementCount) {
myList.removeChild(myList.firstChild);
}
}
ul li.checked {
background: #888;
color: #fff;
text-decoration: line-through;
}
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
<!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>To Do List</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="index.css">
</head>
<body>
<form id="form">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6 col-md-8 mt-5">
<div class="card">
<div class="card-body">
<div class="input-group">
<input class="form-control" type="text" id="text" placeholder="What will you do today?">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit" id="submit">Ekle</button>
<button onclick="myFunction()" type="submit" id="reset" class="btn btn-outline-secondary">Sıfırla</button>
</div>
</div>
</div>
</div>
<div class="card mt-3">
<div class="card-header">My List</div>
<ul id="myList" class="list-group list-group-flush">
</ul>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript" src="index.js"></script>
</body>
</html>

How do I render values of input elements into a div correctly?

I'm trying to grab an input value with javascript and render it into a div element. What do I do to make it work?
I'm using querySeclector to grab the input value. When I hardcode it like this:
document.getElementById("result").innerHTML = "Hello World";
It works but doesn't when I replace "Hello World" with the variable that stores the input value and when I do a console.log, I get nothing back even though there are no errors.
HTML
<body>
<div id="container">
<div id="values">
<input id="firstinput" type="text" placeholder="Enter 2 positive figures">
<button id="submit">Submit</button>
</div>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
JAVASCRIPT
let submitButton = document.querySelector("#submit"),
showResult = document.getElementById("result").innerHTML,
weightsForLeftAndRightSides = document.querySelector("#firstinput").value;
submitButton.addEventListener("click", weightBalancer);
function weightBalancer() {
showResult = weightsForLeftAndRightSides;
console.log(weightsForLeftAndRightSides);
}
you need get input value inside weightBalancer when sumbit button clicked
function weightBalancer() {
var weightsForLeftAndRightSides = document.querySelector("#firstinput").value;
document.getElementById("result").innerHTML = weightsForLeftAndRightSides;
}
if i understood your question, you can write this code to put the user input in div tag:
<!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">
<title> Test</title>
<script >
/*to put the user input in div tag*/
function myFunction(){
const userInput=document.querySelector("#firstinput");
const output=document.querySelector("#result");
output.innerHTML=userInput.value;//this parte overwrite the first input
}
</script>
</head>
<body>
<body>
<div id="container">
<div id="values">
<input id="firstinput" type="text" placeholder="Enter 2 positive figures">
<button id="submit" onclick="myFunction()">Submit</button>
</div>
<div id="result"></div>
</div>
</body>
</html>
Hope this helps

How to detect where I was clicked before click on submit button

I have been facing a problem in my project.
Here in my project I want the position where mouse was clicked after I clicked on facebook upload button.
For example
Here In the image say I was clicked Hello text I want the position of Hello Text after I click on the facebook upload button and add image after the text. Similarly as the Hello Test case. This is where I have been trying
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<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>Laravel</title>
<!-- Fonts -->
</head>
<body>
<div id="container">
<h1>Medium Editor</h1>
<form action="{{ route('editor') }}" method="post">
{{ csrf_field() }}
<div class="editable">
<textarea class="form-control textarea" name="description_en" id="description_en" ></textarea>
</div>
<input type="submit" value="submit">
</form>
<button id="facebookUpload">Facebook Upload</button>
</div>
<script type="text/javascript" src="{{ asset('js/jquery.js') }}"></script>
<script>
jQuery(document).ready(function(){
jQuery("#facebookUpload").focusin(function(e){
var posX = jQuery(this).prev().focusout().position().left;
var posY = jQuery(this).prev().focusout().position().top;
jQuery('.medium-editor-element').append('<img id="theImg" src="https://cdn.filestackcontent.com/jHNwCAMlTzujKkeLIyrq" style="width:100px;height:100px;left:'+ (e.pageY - posY) + ';top:'+ (e.pageX - posX) +'" />')
console.log((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
});
</script>
</body>
</html>
But this is not working. It is added image at the bottom in all case.
Here is the Example
I didnot find a solution for this. Plz help me. Thank You.
Next time, please mention all relevant details about your question. Using a plugin which replaces a <textarea> by a <div contentEditable> is quite important.
There was 2 problems with your attempt:
You can't add an image in a <textarea>. But in a <div contentEditable>, yes.
You won't be able to append anything based on x/y click coordinates. You need to target an element to append something before, after or inside.
So here is a solution, using the event target, to store the clicked element.
You have to check if that target is a <p>. Because if it's a <div>, it may be the editor's div... And that would be annoying to append an image after it.
So if it's not the case, keep that element in memory using a variable.
Then on the FB button click, you can append the image.
var editor = new MediumEditor('.editable textarea');
var clickedElement;
$(".medium-editor-element").on("click",function(e){
// Making sure the click did not occured on the editor itself.
if(e.target.tagName == "DIV" && $(e.target).hasClass("medium-editor-element")){
return;
}
// Keep that clicked element in memory...
clickedElement = $(e.target);
});
$("#facebookUpload").on("click",function(){
if(typeof(clickedElement) != "undefined"){
// Append an image after the last clicked element, if any.
clickedElement.after("<img src='https://via.placeholder.com/80x80?text=IMG'>");
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/medium-editor/5.23.3/css/medium-editor.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/medium-editor/5.23.3/css/themes/beagle.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/medium-editor/5.23.3/js/medium-editor.min.js"></script>
<div id="container">
<h1>Medium Editor</h1>
<form action="" method="post">
<div class="editable">
<textarea class="form-control textarea" name="description_en" id="description_en" ></textarea>
</div>
<input type="submit" value="submit">
</form>
<button id="facebookUpload">Facebook Upload</button>
</div>

Unstable result in jsp while using javascript

I am currently working in jsp. I need to get the value of input on text box while a buttton is clicked. My code is given below. While running it produces output which disappears in seconds. I need a stable output (text in textbox) when button is clicked.
<html>
<head>
<style type="text/css">
body {
background-color: #cccccc;
}
tab{ padding-left: 4em; }
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<form>
<title>Businesscard Management</title>
</head>
<body>
<br><br><br><br><br><br>
<h2> Search : <input type="text" class="textbox" size="75" id="myText" autofocus="true" name="searchinput"/></h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("myText").value="ertyu";
}
</script>
</body>
</html>
First of all you have some errors in your code markup. You have just one opened <form> tag inside of <head> tag. Also I noticed that you're trying to set styles for tab but this is not appropriate tag. And you forgot to close </html> tag. Be careful when writing code, better to use code indention for better reading and it could prevent plenty of errors.
regarding your code:
<html>
<head>
<style type="text/css">
body {
background-color: #cccccc;
}
tab {
padding-left: 4em;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Businesscard Management</title>
</head>
<body>
<br><br><br><br><br><br>
<form action="/">
<h2> Search : <input type="text" class="textbox" size="75" id="myText" autofocus="true" name="searchinput"/></h2>
<input type="button" onclick="myFunction()" value="Try it"/>
<p id="demo"></p>
</form>
<script>
function myFunction() {
document.getElementById("myText").value = "ertyu";
}
</script>
</body>
</html>
I've move <form> tag to it desired position. And replaced <button> with <input type="button"> to prevent form submitting. So regarding your code when you press Try it button you will assign "ertyu" text to the input value. And if you want to get value of it, just use document.getElementById("myText").value

Load image in DIV from url obtained from a TEXT BOX

I am trying t load an image into div tag from a url which is obtained from a textbox.My current file is as follows..I don't know what else to be done
<html lang="en">
<head>
</head>
<body>
<input type="text" class="imageURL1">
<div class="ImageContainer">
image will appear here:
</div>
</body>
</html>
Using pure javascript you can load the image as follows. I am using the onChange event to detect whether url has been supplied to the textbox or not. On pressing Enter key, the image will be loaded in the div.
function addImage()
{
var url = document.getElementsByClassName("imageURL1")[0].value;
var image = new Image();
image.src = url;
document.getElementsByClassName("ImageContainer")[0].appendChild(image);
}
<html lang="en">
<head>
</head>
<body>
<input type="text" class="imageURL1" onChange="addImage();">
<div class="ImageContainer">
image will appear here:
</div>
</body>
</html>
You can try something like this.
$(document).ready(function(){
$("#Submit").click(function(){
var image_url = $(".imageURL1").val();
$(".ImageContainer").html("<img src='"+image_url+"' width='200'>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="imageURL1">
<button id="Submit">Submit</button>
<div class="ImageContainer">
</div>
Js fiddle example -> http://jsfiddle.net/0kvxpnmv/
$('<img src="'+image_url+'">').load(function() {
$(this).appendTo('.ImageContainer');
});
JS Fiddle
Use php
index.php file
<form action="GetURL.php" method="post">
<input type="text" name="url">
<input type="submit">
</form>
Now when they click submit it will take you to the new page
GetURL.php
$image_url = $_REQUEST['url'];
<html lang="en">
<head>
</head>
<body>
<input type="text" class="imageURL1">
<div class="ImageContainer">
<?php echo '<img src="{$image}"/>'; ?>
</div>
</body>
</html>
On this page you can see that in your imageContainer class you have the image url being posted with PHP
The best way to handle this from here would be to have the form on the same page as the image and have it post the url with ajax.
So you would type in the url to the textbox and when your done it refreshes the image url.
How about using a button to call a funtion that'll change the image src with url in the text box
HTML
<html lang="en">
<head>
</head>
<body>
<input type="text" class="imageURL1">
<button onclick="func()">Load image</button>
<div class="ImageContainer">
<img src="" id="imgContainer">
</div>
</body>
</html>
javascript
(function(){
var func = function(){
var url = $(".imageURL1").val()
$('#imgContainer').attr('src',url)
}
})();
Here's the jsFiddle with jQuery and without jQuery
Please see my code below, on the change event of the text input, it would create an jQuery img tag then add then use the URL from the input as the source and clear the contents of the output div. Once the image is loaded, it will replace the content of the output div.
$('.imageURL1').change(function() {
var $img = $('<img/>');
$img.attr('src', $(this).val());
$img.load(function() {
$('.ImageContainer').html(this);
});
});
This solution requires jQuery.
Working fiddle here.

Categories