Set an image from Firebase as the background of div via jQuery - javascript

I'm trying to get an image from fire base and set it as the background of a div. Does anyone know how to do that? I tried all of my ideas and they did not work. Can someone provide any examples?
<div class="museBGSize rounded-corners grpelem" id="u525"></div>
I tried it this way and it didn't work:
fbRef4.on("child_added", snap => {
var image = snap.child("Image").val();
//concatenated the img tag using the image variable at the top
$("#tableBody3").append("<img src=" + image + "/img>");
});

hello every one i found an answer for it and will post the answer just in case if some one want to know
((my html))
<div class="museBGSize rounded-corners grpelem" id="u525"><!-- simple frame --></div>
((my js))
var fbRef4 = firebase.database().ref().child("slide");
fbRef4.on("child_added", snap => {
var image = snap.child("Image").val();
var newimgsrc = 'image' + (new Date().getTime());
var newimg = $('#u525');
$('#u525').css("background-image", "url("+image+")");
newimg.css({'background-image': 'url('+image+')'});
newimg.show();
});
((my firebase))
-slide
-asdasdasd
Image:"https://firebasestorage.googleapis.com/v0/b/awe..."

Related

DOM background-Image add

I'm a beginner.
I encounter a small problem which is I cannot add an image to my div block.
here is my HTML code
<span class = 'memepic'>
<img src ="https://encryptedtbn0.gstatic.com/imagesq=tbn:ANd9GcTmvCGIVavqB6jVObiS1sqkvwlzYgpjCVfWBg&usqp=CAU">
</span>
and I wrote my js code is like this one
//it is my <span> id
const img = document.getElementsByClassName('memepic')
//it is my divblock id
const memebox = document.querySelector('#meme')
for(i of img){
i.addEventListener("click", function(e) {
console.log(e)
memebox.style.backgroundImage = 'url("e.path[0].currentSrc")';
});
}
the error shows my console is
e.path[0].currentSrc:1 GET file:///C:/Users/kevin/Desktop/bootcamp/officialclass/meme%20generator/e.path[0].currentSrc net::ERR_FILE_NOT_FOUND
my purpose is when I click that picture, that picture will show on my divblock which is in the center of the screen.
I checked the path[0].currentSrc is correct.
and it will show the picture if I replace 'e.path[0].currentSrc' to the content inside the 'e.path[0].currentSrc'.
like this
memebox.style.backgroundImage = 'url("https://encryptedtbn0.gstatic.com/imagesq=tbn:ANd9GcTmvCGIVavqB6jVObiS1sqkvwlzYgpjCVfWBg&usqp=CAU");
Hey can you try this code in for loop :
`url(${e.srcElement.currentSrc})`
Javascript doesn't parse variables that are inside a string, so you're asking for the background URL to literally be set as "e.path[0].currentSrc".
Instead of this:
memebox.style.backgroundImage = 'url("e.path[0].currentSrc")';
Do this:
memebox.style.backgroundImage = 'url("' + e.path[0].currentSrc + '")';

Get image preview to another div on click

I have a little problem with my image preview, because I would like get photo from #ImagePreview to #photo2 on click confirm button.
https://jsfiddle.net/0xd4odyf/3/
HTML
<img id="ImagePreview">
<input type="file" class="InputFile" onchange="document.getElementById('ImagePreview').src =window.URL.createObjectURL(this.files[0])">
<div id="photo2"></div>
<button id="confirm">confirm</button>
You can get the src attribute of the image (#ImagePreview) you selected and then set it as background-image attribute of the div(#photo2).
$("#confirm").click(function()
{
var img = $('#ImagePreview').attr('src');
$("#photo2").css('background-image','url(' + img + ')');
});
Example : https://jsfiddle.net/0xd4odyf/5/
Maybe you've already solved this problem, but perhaps someone will need it. Above problem is soloved using jquery, and I show solution using pure javascript.
let confirmButton = document.getElementById('confirm');
let photo2 = document.getElementById('photo2');
confirmButton.addEventListener('click', function(e){
let srcAttr = document.getElementById('ImagePreview').getAttribute('src');
let newImg = document.createElement('img');
newImg.setAttribute('src', srcAttr);
photo2.appendChild(newImg)
})
And the fiddle: https://jsfiddle.net/1Lzpy42b/

PhotoSwipe: closing gallery animates wrong rectangle (thumbnail)

I'm new to Javascript and I have a problem implementing PhotoSwipe plugin:
I'm trying to implement PhotoSwipe plugin for a web page using jQuery. Most of it is working correctly (opening a gallery, navigating slides). The problem happens when I close the gallery. The problem:
I click on image 1, this opens PhotoSwipe lightbox, I navigate to slide 2, and then close the gallery. This closes the gallery. But closing animation is played for image 1, while I am expecting it to be played for Image 2.
It works correctly on PhotoSwipe demo page, so it is an error in my code. If I copy/paste demo page Javascript code, it works correctly.
I believe I am missing some code that binds currently shown slide with respective thumbnail. My main issue with demo page is: I have a hard time understanding vanilla JS demo, what part is responsible for what action. Please help me find missing functionality.
Here's my code for PhotoSwipe "click to start gallery" event:
$('.my-gallery').each( function() {
var $pic = $(this);
var items = itemArray;
var $pswp = $('.pswp')[0];
$pic.on('click', 'figure', function(event) {
event.preventDefault();
var $index = $(this).index();
var options = {
index: $index,
getThumbBoundsFn: function(index) {
// get element we clicked on to determine its position in window
var thumbnail = event.target;
// get position of element relative to viewport
var rect = thumbnail.getBoundingClientRect();
// get window scroll Y
var pageYScroll = window.pageYOffset ||
document.documentElement.scrollTop;
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
}
}
// Initialize PhotoSwipe
var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, items, options);
lightBox.init();
});
});
My gallery (stripped down to 2 slides):
<div class="row my-gallery" itemscope itemtype="http://schema.org/ImageGallery" id="img-gallery">
<figure itemprop="associatedMedia" itemscope="" itemtype="http://schema.org/ImageObject">
<a href="images/nature/DSC_7216.jpg" itemprop="contentUrl" data-size="1200x795">
<img src="images/nature/DSC_7216_t.jpg" itemprop="thumbnail">
</a>
</figure>
<figure itemprop="associatedMedia" itemscope="" itemtype="http://schema.org/ImageObject">
<a href="images/nature/DSC_7218.jpg" itemprop="contentUrl" data-size="1200x795">
<img src="images/nature/DSC_7218_t.jpg" itemprop="thumbnail">
</a>
</figure>
</div>
Item array is generated from JSON:
[
{
"src": "images/nature/DSC_7216.jpg",
"msrc": "images/nature/DSC_7216_t.jpg",
"w":1200,
"h":795
},
{
"src": "images/nature/DSC_7218.jpg",
"msrc": "images/nature/DSC_7218_t.jpg",
"w":1200,
"h":795
}
]
JSON is hardcoded into a p element, is parsed using jQuery parser:
var itemArray = jQuery.parseJSON($(imageListSelector).html());
You can find the full page with problem on GitHub
PhotoSwipe demo on Codepen
Can you help me find what I am missing?
Edit:
I've tracked the issue down to this part of code in the original PhotoSwipe demo:
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
If I replace this part with a fixed thumbnail selector (like I have in my jQuery - it contains "event target" reference), I can force PhotoSwipe demo to repeat my behavior - zoom out gets performed on same image. Not exactly the same thing that happens in my case, but close enough.
Now I just need to figure out how to change my getThumbBoundsFn to use actual thumbnail reference instead of event.target... I'll probably have to update my itemArray to include links to figure element, like the original PhotoSwipe demo. As I wrote earlier, I'm still new to Javascript, so figuring out some things takes time. Any help will be appreciated.
Figured it out myself. I really screwed things up by using event.target. The correct way of working with PhotoSwipe requires me to provide actual DOM element instead of a fixed one (like event target).
The correct way of doing this is just like demo:
save DOM element (selector) when creating itemArray
use DOM element from itemArray in order to provide correct element to calculate bounding rectangle.
Correct jQuery code:
var gallerySelector = "#img-gallery";
var imageListSelector = "#imageList";
// parse server reply (JSON, imitated, saved into a tag)
var itemArray = jQuery.parseJSON($(imageListSelector).html());
var index = 1;
// HTML structure of gallery image
var imageHTML = "<figure class=\"col-xs-12 col-sm-6 col-md-4\" " +
"itemprop=\"associatedMedia\" itemscope " +
"itemtype=\"http://schema.org/ImageObject\">\n" +
"<a href=\"{imageSource}\" itemprop=\"contentUrl\" data-size=\"{imageSize}\">\n" +
"<img class=\"img-responsive\" src=\"{imageThumb}\" itemprop=\"thumbnail\" />\n" +
"</a>\n</figure>";
// generate images based on JSON request (imitated) and appended them to the page
itemArray.forEach(function(item) {
var imageTags = imageHTML.replace("{imageSource}", item.src);
var imageTags = imageTags.replace("{imageSize}", (""+item.w+"x"+item.h));
var imageTags = imageTags.replace("{imageThumb}", item.msrc);
$(gallerySelector).append(imageTags);
item.el = $(gallerySelector + " figure:last img")[0];
});
$('.my-gallery').each( function() {
var $pic = $(this);
var $pswp = $('.pswp')[0];
$pic.on('click', 'figure', function(event) {
event.preventDefault();
var $index = $(this).index();
var options = {
index: $index,
getThumbBoundsFn: function(index) {
// get element we clicked on to determine its position in window
//var thumbnail = event.target;
var thumbnail = itemArray[index].el;
// get position of element relative to viewport
var rect = thumbnail.getBoundingClientRect();
// get window scroll Y
var pageYScroll = window.pageYOffset ||
document.documentElement.scrollTop;
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
}
}
// Initialize PhotoSwipe
var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, itemArray, options);
lightBox.init();
});
});
Summary of changes:
added item.el property, which saves last added element when it is appended to the gallery (in my case - figure img, since I need the img object to calculate its bounding rectangle).
Replaced event.target with respective itemArray[index].el (previously saved node).
Hope this helps! It took me a couple of hours and some trial and error with PhotoSwipe demo page to figure this out.

Displaying Images in Javascript

OK, so I'm making a website in HTML, and it's working great, but I need to know how to display images on the page in javascript. I have in my website where there is a part on the homepage called news, and it's going to display an image about the topic, but I don't know how to display the image. When I use other website's ways, the image just displays as a square with a ? in the middle. Please help!!
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.appendChild(content);
I got these answers from:
How to display image with javascript?
How to append data to div using javascript?
This will work:
DEMO
javascript:
var i = document.getElementById('test'); //get the element to put the picture in
i.innerHTML = '<img src="http://pathtopicture.jpg"></img>'; // append the picture to the divs inner HTML
HTML:
<div id="test"></div>
Or without HTML in the first place (of course you need html and body tag...)
DEMO2
Code:
var i = document.createElement('div');
i.id = 'test';
document.getElementsByTagName('body')[0].appendChild(i);
i.innerHTML = '<img src="http://pathtopicture.jpg"></img>';

is it possible to display pictures in a popup.php window, using the src from the main page?

I have a page with pictures, which I want to displayed in a popup.php when clicking on them.
I want the popup window to display a picture(the one I'm clicking on), some text, and a print button.
I'm doing this on the page:
<img src="graphics/picture1.png" width="340" height="200" border="0"/>
In the JS file:
function popup()
{
window.open('popup.php', 'window', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
}
function showImg(img)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
}
And in the popup.php:
<img src="graphics/picture03.png" onload="showImg(this)" />
There should be an obvious way, but I can't find it.
I would think adding the image name and text content to the URL would be the obvious way.
popup.php?image=myImage.gif&text=Say%20something%20witty%20here
Well, you'll want to have your popup contain a holder for the image (which it seems like you already have), but you'll also need to have a holder for your text. Your popup.php should have something like <div id="textHolder"></div> - then your javascript function needs to accept the appropriate text as well as populate it into the textHolder div.
I'm not sure how you're calling these JS functions, or from where - so some of the code might need to change - it should be something to the tune of....
function showImg(img, textHolderObj, text)
{
var imageSrc = "imageName/imagePath.png";
if(img.src != imageSrc){
img.src = imageSrc;
}
textHolderObj.innerHTML= text
}
If is that simple, you could create it:
var win = window.open('', 'win', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=520,height=400,left=350,top=100');
var img = win.document.createElement('img');
img.src = 'image.png';
img.alt = 'Some text';
var label = win.document.createElement('p');
label.innerHTML = 'Some text';
var button = win.document.createElement('a');
button.href = 'javascript:window.close()';
button.innerHTML = 'Close';
win.document.body.appendChild(img);
win.document.body.appendChild(label);
win.document.body.appendChild(button);
I don't get the question too well. You want to access a function that was defined in the page that opened a popup? You should be able to use opener.showImg(this)
your popup has no idea what image you clicked on. you need to do this:
onClick="popup('imgSrc')"
and in your window reference:
window.open('popup.php?imgSrc='+imgSrc, ...
then... your popup window has to run off of url vars, but php now knows what its looking for:
<?php echo '<img src="' . $_GET["imgSrc"] . '" />'; // this is going to load the image, so you don't need the onLoad()
It is possible to create a new popup window using a variable
top.mydocument=window.open('','window','toolbar=no,location=no,
status=no,menubar=no,scrollbars=no,resizable=no,
width=520,height=400,left=350,top=100');
and then use document.write to write the content:
top.mydocument.document.write(
'<html><head></head>'
+'<body bgcolor=white onLoad="self.focus()">'
+'imageName/imagePath.png'
+'</body></html>'
)
Make sure you close it.
top.mydocument.document.close()

Categories

Resources