showing an img in a div after upload - javascript

I am trying to upload an image with javascript and display it in a div but the method I'm using right now is not working. I tried using both an img tag and just setting it as a background-image but both won't show the img in the div but when I inspect the div it shows that the URL has successfully been inserted. Where did I go wrong? Any help is appreciated. Thanks in advance.
const image_input = document.querySelector("#image_input");
image_input.addEventListener("change", function() {
const reader = new FileReader();
reader.addEventListener("load", () => {
const uploaded_image = reader.result;
$('.imgCon').attr("background-image", `url(${uploaded_image})`);
$('.imgCon2 img').attr("src", `url(${uploaded_image})`);
});
reader.readAsDataURL(this.files[0]);
});
.imgCon {
position: absolute;
top: 30%;
width: 40%;
height: 40%;
border-radius: 8px;
background-color: #000000;
/* background-size: 100%; */
background-position: center;
background-size: cover;
}
.imgCon2 {
position: absolute;
top: 30%;
right: 0%;
width: 40%;
height: 40%;
border-radius: 8px;
background-color: #000000;
/* background-size: 100%; */
background-position: center;
background-size: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" title="" id="image_input" accept="image/png, image/jpg">
<div class="imgCon">
</div>
<div class="imgCon2">
<img src="" />
</div>

Change to:
$('.imgCon').css("background-image", `url(${uploaded_image})`);
$('.imgCon2 img').attr("src", uploaded_image);
attr will set an attribute on the element i.e <div background-image="url(...)" and src="url(...)" is incorrect.

Related

Image aspect ratio is just barely different than the image in a new tab

I have an image inside a container. The image has object-fit contain set to it in order to maintain aspect ratio. It does this, but just shy away from perfect.
When I open the image in a new tab and compare it with the one in my browser, the browser image shows the slightest blurriness compared to the one in the new tab.
I've tried setting max-width, max-height, to the image and all gave the same result. The image dimensions ended up being different by a few decimal points which caused blurriness.
I want the image to be inside the container while maintaining aspect ratio like how it is in a new tab.
HTML
"use strict";
const $ = (selector) => document.querySelector(selector);
const gallery = $(".gallery").childNodes;
const slides = $("#my_modal").childNodes;
$(".gallery").addEventListener("click", evt => {
for ( let i in gallery ) {
if ( evt.target == gallery[i] ) {
$("#my_modal").style.display = "initial";
slides[i].style.display = "initial";
$("#my_modal").addEventListener("click", evt => {
if ( evt.target == $("#my_modal") ) {
$("#my_modal").style.display = "none";
slides[i].style.display = "none";
}
});
}
}
});
* { box-sizing: border-box; }
html {
margin: 0;
padding: 0;
color: white;
font-size: 16px;
}
body {
overflow: hidden;
background-color: black;
}
.gallery {
text-align: center;
}
.gallery img {
width: 100%;
max-width: 360px;
height: 480px;
object-fit: cover;
cursor: pointer;
}
.modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
overflow: auto;
margin: 0;
padding: 0;
}
.my_slides {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 0;
margin: 0;
height: 90%;
width: 90%;
background-color: gray;
}
.my_slides img {
width: 100%;
height: 100%;
object-fit: contain;
}
<body>
<div class="gallery">
<img src="https://material.angular.io/assets/img/examples/shiba2.jpg" alt="">
</div>
<div id="my_modal" class="modal">
<div id="boros1" class="my_slides">
<img src="https://material.angular.io/assets/img/examples/shiba2.jpg" alt="">
</div>
</div>
</body>
Here is my JSFiddle https://jsfiddle.net/38rauwnf/
I suggest replicating on your machine in order to see the whole browser and opening the image in a new tab and comparing the images. The blue eyeball will be blurrier than the new tab.
Here is the image in the browser https://i.imgur.com/k2550RW.png
Here is the image in the new tab https://i.imgur.com/qwFybbj.png
EDIT: My problem has been solved on this post My images are blurry in Chrome but not Firefox w/ video demonstration

How to create a slide of background images using Pure Javascript or a pure Javascript library

I'd like to make the below in a way that I can have two images slide in the background but have I'm stuck on how to implement a slide of background images. Kindly assist, any assistance will be highly appreciated.
#header-image {
background-image: url('/images/photography1.jpg');
width: 100%;
border: none;
padding: 0;
margin: 0;
background-position: bottom center;
background-repeat: no-repeat;
background-size: cover;
height: 100vh;
position: relative;
}
<div id="header-image">
<div class="overlay" data-aos="fade-down-right">
<h1>Photography Logo</h1>
</div>
</div>
I made an example for you using javascript, as well as modified your html and css. Was such a result necessary? If you have any questions, please let me know.
let anime = document.querySelector('#header-image');
var step = 0;
function animate() {
if (step > -200) {
anime.style.transform = 'translateX('+ step +'vw)';
} else {
anime.style.transform = 'transformX(100vw)';
step = 100;
}
}
setInterval(function () {
step = step - 100;
animate();
}, 5000);
body {
padding: 0;
margin: 0;
}
#header {
overflow: hidden;
}
#header-image {
border: none;
width: 200vw;
height: 100vh;
transition: 1s;
display: flex;
}
#photo_section_one {
background-image: url('https://img.desktopwallpapers.ru/newyear/pics/wide/1920x1200/5f7ff83acdb7b743fb61468954e9c511.jpg');
width: 100vw;
background-position: bottom center;
background-repeat: no-repeat;
background-size: cover;
height: 100%;
}
#photo_section_two {
background-image: url('https://lh3.googleusercontent.com/proxy/N_97o7XR3tJd8Thp4vFQxXqqQVMSgBNhjGlvvHa9bDnpW-i4v6J9EElWWMSC8qumCbDAfvAjroBDWBu8F1HPl-hZX1BsYOk-wDNO26pT19W90o8n22aABvQ');
width: 100vw;
background-position: bottom center;
background-repeat: no-repeat;
background-size: cover;
height: 100%;
}
<div id="header">
<div id="header-image">
<div id="photo_section_one">
<div class="overlay" data-aos="fade-down-right">
<h1>Photography Logo</h1>
</div>
</div>
<div id="photo_section_two">
<div class="overlay" data-aos="fade-down-right">
<h1>Photography Logo</h1>
</div>
</div>
</div>
</div>
Second solution using an array of images. The images change as on the site you showed.
let anime = document.querySelector('#header-image');
let images = ['https://vjoy.cc/wp-content/uploads/2019/08/1-39.jpg', 'https://img.desktopwallpapers.ru/newyear/pics/wide/1920x1200/5f7ff83acdb7b743fb61468954e9c511.jpg'];
let index = 0;
setInterval(function(){
anime.style.backgroundImage = 'url(' + images[index] + ')';
index++;
if (index >= images.length) {
index = 0;
}
}, 5000);
* {
padding: 0;
margin: 0;
}
#header {
overflow: hidden;
}
#header-image {
border: none;
height: 100vh;
transition: 1s;
background-image: url('https://img.desktopwallpapers.ru/newyear/pics/wide/1920x1200/5f7ff83acdb7b743fb61468954e9c511.jpg');
width: 100%;
background-position: bottom center;
background-repeat: no-repeat;
background-size: cover;
}
<div id="header">
<div id="header-image">
<div id="photo_section_one">
<div class="overlay" data-aos="fade-down-right">
<h1>Photography Logo</h1>
</div>
</div>
</div>
</div>
As far as I'm aware you cannot do exactly what you are asking for. But, you can create something similar though z-index and absolute positioning, some css, and some js. You would have to create a div behind the text and animate it using css, while using some js to make it continuously loop.
setInterval(function() {
if (document.getElementsByClassName("slide-pos-1")[0] != undefined) {
document.getElementsByClassName("background-slide")[0].classList.add("slide-pos-2")
setTimeout(function() {
document.getElementsByClassName("background-slide")[0].classList.remove("slide-pos-1")
document.getElementsByClassName("background-slide")[0].classList.remove("slide-pos-2")
}, 1500)
} else {
document.getElementsByClassName("background-slide")[0].classList.add("slide-pos-1")
}
}, 6000)
html,
body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
.background-slide {
position: absolute;
top: 0;
left: 0;
width: 300%;
height: 100%;
display:flex;
transform:translate(0,0);
transition: transform 0s ease-out;
}
.slide-pos-1{
transform:translate(calc(-100% / 3),0);
transition: transform 1s ease-out;
}
.slide-pos-2{
transform:translate(calc(-200% / 3),0);
transition: transform 1s ease-out;
}
.header-image {
width: 100%;
height: 100%;
}
.overlay{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.image {
flex:1;
}
img {
object-fit: cover;
width:100%;
height:100%;
margin:0;
}
<div class="header-image">
<div class="background-slide slide-pos-1">
<div class="image"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png" /></div>
<div class="image"><img src="https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg" /></div>
<div class="image"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png" /></div>
</div>
<div class="overlay">
<h1>Photography Logo</h1>
</div>
</div>
Also, this one doesn't slide the text along with the image, and the slide direction is the same. Credit of s.kuznetsov for making me realize that and revise my answer.

Changing background-image to sql image

Is there a way to set the background-image: url(--SET THIS--), to an sql picture?
I was thinking about somthing like this:
$img = $MysqliHandler->query(SELECT avatar FROM account WHERE username="'.$_SESSION['name'].'"';
And then somehow change the url to: '.base64_encode( $img[0]['avatar'] ).'
Right now I just have a simple change avatar function, but I want to save this to a specific "'.$_SESSION['name'].'", so that user always have that avatar, and are able to change it.
Should I use ajax, and then link the new image to another php, and run a update image sql function there?
$("#ChangeImg").click(function(e) {
$("#imageUpload").click();
});
function fasterPreview(uploader) {
if (uploader.files && uploader.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(uploader.files[0]);
reader.onloadend = function(){
document.getElementById("imgDivEdit").style.backgroundImage = "url(" + reader.result + ")";
}
}
}
$("#imageUpload").change(function() {
fasterPreview(this);
});
#imageUpload {
display: none;
}
.container {
position: relative;
width: 125px;
height: 125px;
}
.overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 125px;
width: 125px;
opacity: 0;
transition: .5s ease;
background-color: rgba(11, 90, 180, 0.795);
border-radius: 50%;
}
.container:hover .overlay {
opacity: 0.7;
}
.text {
color: white;
font-size: 20px;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align: center;
cursor: pointer;
}
#imgDivEdit {
width: 125px;
height: 125px;
background-image: url("https://www.whatsappprofiledpimages.com/wp-content/uploads/2019/01/Nice-Whatsapp-DP-Profile-Images-4-300x300.jpg");
background-position: 5px -5px;
border-radius: 50%;
background-size: cover;
}
<div id="avatar"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="imgDivEdit"></div>
<div id="ChangeImg" class="overlay">
<div class="text">Change Image</div>
</div>
</div>
</div>
<input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture>
So I use data:image/jpeg;base64,'.$_SESSION['avatar'].', as background, in a separate .php file, and this is ofc. included in my .php file:
#imgDivEdit{
width: 125px;
height: 125px;
background-image: url("data:image/jpeg;base64,'.$_SESSION['avatar'].'");
border-radius: 50%;
background-size: cover;
}
Then I made a if statement, that updates the sql and then retrieve it and update session.
$URL = $_SERVER['REQUEST_URI'];
if(isset($_POST['Save']) && !empty($_POST['Save']))
{
if($_FILES["imageUpload"]["size"]>1010000 || $_FILES["imageUpload"]["size"]==0 )
{
echo"<h3 style='color:#db4409'>Failed to upload image.</h3>";
}
else{
$image=addslashes(file_get_contents($_FILES['imageUpload']['tmp_name']));
$sql='UPDATE accounts SET avatar = ("'.$image.'") WHERE username ='.$_SESSION['name'].'';
$query = $MysqliHandler->query($sql);
$sql='SELECT avatar FROM accounts WHERE username ='.$_SESSION['name'].'';
$avatar = $MysqliHandler->query($sql);
$_SESSION['avatar'] = base64_encode( $avatar[0]['avatar'] );
header("Refresh:0; url=$URL");
exit();
}
}
I made a save option to run all this when a image is uploaded, and showed:
<form method="POST" enctype="multipart/form-data">
<input id="imageUpload" type="file" name="imageUpload" placeholder="Photo" accept="image/x-png,image/gif,image/jpeg" required="" capture>
<div id="Change" hidden>
<input type="submit" name="Save" id="Save" value="Save" class="btn btn-info Save"/> <p style="font-size:11px;">Max size: 1Mb</p>
</div>
</form>
.js
$("#imageUpload").change(function() {
$("#Change").show();
});

Arrays are not working with If Statement

New on StackOverFlow - Just have a simple question.
Could you please let me know why it is not changing the color of Div element when the condition is true for the If Statement. .MeTest's display property is Block - Also, no error messages are in the Console.
Here is my test code :
var x = document.getElementsByClassName("MeTest");
if (x[0].style.display == 'block')
{
document.getElementsByClassName("haveIt")[1].style.backgroundColor = "red";
}
#MeTest {
position: fixed;
height: 200px;
width: 200px;
background-color: #fdacc3;
}
div {
background: #4dd329;
border: 1px solid white;
height: 200px;
width: 200px;
display: block;
}
.MeTest {
display: block;
}
<div class="MeTest"></div>
<div class="testThis" style="float: right;"></div>
<div class="haveIt" style="position: fixed; top: 400px;"></div>
Thanks!
You have only one element with the class name haveIt. So you should make the following change:
document.getElementsByClassName("haveIt")[0]
Furthermore, in orde the condition you check to be true, you should define a style with display block for the div with class MeTest.
var x = document.getElementsByClassName("MeTest");
if (x[0].style.display == 'block')
{
document.getElementsByClassName("haveIt")[0].style.backgroundColor = "red";
}
#MeTest{
position: fixed;
height: 200px;
width: 200px;
background-color: #fdacc3;
}
div{
background: #4dd329;
border: 1px solid white;
height: 200px; width: 200px;
display: block;
}
.MeTest{
display: block;
}
<div class="MeTest" style="display: block;"></div>
<div class="testThis" style="float: right;"></div>
<div class="haveIt" style="position: fixed; top: 200px;"></div>
PS: I changed the value of top from 400px to 200px, in order to be seen when you run the snippet.
Update
I see that in my first question about statements, you changed to
display to Block in the HTML DOM - When I call that element in the Css
stylesheet and change the Display to Block, it doesn't work that way.
Any thoughts why it is happening?
It doesn't work since the display property of the element is imposed by the style sheet, it's not a value included in the style attribute of the html element. That you can do in this case, it to make use of getComputedStyle method like in the below snippet.
var x = document.getElementsByClassName("MeTest");
var display = window.getComputedStyle(x[0],null)
.getPropertyValue("display");
if (display == 'block'){
document.getElementsByClassName("haveIt")[0].style.backgroundColor = "red";
}
#MeTest{
position: fixed;
height: 200px;
width: 200px;
background-color: #fdacc3;
}
div{
background: #4dd329;
border: 1px solid white;
height: 200px; width: 200px;
display: block;
}
.MeTest{
display: block;
}
<div class="MeTest"></div>
<div class="testThis" style="float: right;"></div>
<div class="haveIt" style="position: fixed; top: 200px;"></div>
For info regarding the Window.getComputedStyle please have a look [here].1
var x = document.getElementsByClassName("MeTest")[0];
if (getComputedStyle(x).getPropertyValue("display")== 'block')
{
document.getElementsByClassName("haveIt")[1].style.backgroundColor = "red";
}

CSS3 or JAVASCRIPT for hover

I would like to put in evidence a picture (and blur all the rest) when I am over a link. Here my Html:
<body>
<div id="back">
<div id="one"></div>
<div id="two"></div>
</div>
<div id="menu">
one</div>
two</div>
</div>
</body>
and CSS:
#Back{
position: absolue;
background-image: url(images/fond.png);
width: 960px;
height: 600px;
margin: 0 auto;
}
#one{
background-image: url(images/formation.png);
width: 960px;
height: 600px;
z-index:1;
}
#two{
background-image: url(images/experiences.png);
width: 960px;
height: 600px;
z-index:2;
margin-top:-600px;
}
The problem i tried in css with this:
#link1:hover #one{
display:none;
}
And in javascript with this script:
function over(id){
if(document.getElementById(id)){
var objet = document.getElementById(id);
objet.style.display = "none";
}
}
Both doesn t work. I m not super good with the javascript. Thank so much for your help!!!
HTML:
<div id="menu">
link1
link2
</div>
<div class="div0" id="zero">
<div class="div1" id="one"></div>
<div class="div2" id="two"></div>
</div>
CSS:
.div0 {
position: absolute;
top: 30px;
left: 0px;
background-image: url(http://www.sanbarcomputing.com/images/js.jpg);
background-size: 400px 400px;
width: 400px;
height: 400px;
transition: 1s;
}
.div1 {
position: absolute;
top: 30px;
left: 0px;
background-image: url(http://www.sanbarcomputing.com/images/html5-logo.png);
background-size: 200px 200px;
width: 200px;
height: 200px;
transition: 1s;
}
.div2 {
position: absolute;
top: 30px;
left: 200px;
background-image: url(http://www.sanbarcomputing.com/images/class-header-css3.jpg);
background-size: 200px 200px;
width: 200px;
height: 200px;
transition: 1s;
}
JavaScript:
(function () {
var zeroEl = document.getElementById('zero'),
oneEl = document.getElementById('one'),
twoEl = document.getElementById('two'),
link1El = document.getElementById('link1'),
link2El = document.getElementById('link2');
function mouseover (elem) {
elem.style.opacity = '.2';
zeroEl.style.opacity = '.2';
}
function mouseout (elem) {
elem.style.opacity = '1';
zeroEl.style.opacity = '1';
}
document.addEventListener('DOMContentLoaded', function () {
link1El.addEventListener('mouseover', function () {
mouseover(oneEl); }, false);
link2El.addEventListener('mouseover', function () {
mouseover(twoEl); }, false);
link1El.addEventListener('mouseout', function() {
mouseout(oneEl); }, false);
link2El.addEventListener('mouseout', function () {
mouseout(twoEl); }, false);
}, false);
})();
jsfiddle
I could not get the CSS hover solution to work, for whatever reason.
NOTE: This solution uses modern JavaScript techniques that may not be compatible with legacy browsers
EDIT: Updated to use Pavlo's opacity solution, fixed css errors, changed image alignments, made images independent divs
First, assign a class to each link:
<div id="menu">
one</div>
two</div>
</div>
Then, if your css hover does not work, try using jQuery to do the hovering:
$('.link').hover(function() {
//handle mouse enter
}, function() {
//handle mouse leave
});
Refer: http://api.jquery.com/hover/

Categories

Resources