Send an image with js and html into form - javascript

I had a code that looks like this https://cloth.ardive.id/Tshirt/index.html
I want to send the canvas as an image to a form where user need to fill some addon information (name, category) and in this form image from page before is have been displayed and user doesnt need to upload an image anymore. So when they submit the form, submited form is contains their filled information data with the image
because i want to send the canvas that wasnt an image, so we need to generates the canvas into image, then send it to the form.
this is how my form code lookslike (I'm using wordpress and woocommerce, but this code is html). what I want to is navigating into the form page with image already uploaded to this field
<script type="text/javascript">
wpuf_conditional_items.push();
</script>
</li><li class="wpuf-el featured_image" data-label="Gambar"> <div class="wpuf-label">
<label for="wpuf-featured_image">Gambar <span class="required">*</span></label>
</div>
<div class="wpuf-fields">
<div id="wpuf-featured_image-upload-container" style="position: relative;"><div class="wpuf-file-warning"></div>
<div class="wpuf-attachment-upload-filelist" data-type="file" data-required="yes">
<a id="wpuf-featured_image-pickfiles" data-form_id="4244" class="button file-selector wpuf_featured_image_4244" href="https://cloth.ardive.id/buat-produk/#" style="position: relative; z-index: 1;">Select Image</a>
<ul class="wpuf-attachment-list thumbnails">
</ul>
</div>
<div id="html5_1b67l1c6qtdqmec190711k33v46_container" class="moxie-shim moxie-shim-html5" style="position: absolute; top: 0px; left: 0px; width: 106px; height: 29px; overflow: hidden; z-index: 0;"><input id="html5_1b67l1c6qtdqmec190711k33v46" type="file" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;" accept="image/jpeg,.jpg,.jpeg,image/gif,.gif,image/png,.png,image/bmp,.bmp"></div></div><!-- .container -->
<span class="wpuf-help">Masukkan Gambar, gambar harus dengan resolusi tertinggi</span>
</div> <!-- .wpuf-fields -->
<script type="text/javascript">
jQuery(function($) {
new WPUF_Uploader('wpuf-featured_image-pickfiles', 'wpuf-featured_image-upload-container', 1, 'featured_image', 'jpg,jpeg,gif,png,bmp', 8000);
});
</script>
this is the code to save the image that have been already generated from the canvas to users desktop
the code is on canvas2image.js
// sends the generated file to the client
var saveFile = function(strData) {
document.location.href = strData;
}
var makeDataURI = function(strData, strMime) {
return "data:" + strMime + ";base64," + strData;
}
// generates a <img> object containing the imagedata
var makeImageObject = function(strSource) {
var oImgElement = document.createElement("img");
oImgElement.src = strSource;
return oImgElement;
}
var scaleCanvas = function(oCanvas, iWidth, iHeight) {
if (iWidth && iHeight) {
var oSaveCanvas = document.createElement("canvas");
oSaveCanvas.width = iWidth;
oSaveCanvas.height = iHeight;
oSaveCanvas.style.width = iWidth+"px";
oSaveCanvas.style.height = iHeight+"px";
var oSaveCtx = oSaveCanvas.getContext("2d");
oSaveCtx.drawImage(oCanvas, 0, 0, oCanvas.width, oCanvas.height, 0, 0, iWidth, iHeight);
return oSaveCanvas;
}
return oCanvas;
}
return {
saveAsPNG : function(oCanvas, bReturnImg, iWidth, iHeight) {
if (!bHasDataURL) {
return false;
}
var oScaledCanvas = scaleCanvas(oCanvas, iWidth, iHeight);
var strData = oScaledCanvas.toDataURL("image/png");
if (bReturnImg) {
return makeImageObject(strData);
} else {
saveFile(strData.replace("image/png", strDownloadMime));
}
return true;
}
this is another js to classed the function
//export options
$('.exportas').click(function(){
// get type to export
var to = $(this).data('type');
// alert(to);
// get our canvas
var oCanvas = document.getElementById("mycanvas");
// support variable
var bRes = false;
if(to == 'png'){
// export to png
bRes = Canvas2Image.saveAsPNG(oCanvas);
}
if(to == 'jpg'){
// maybe in some old browsers it works only on Firefox
bRes = Canvas2Image.saveAsJPEG(oCanvas);
}if(to == 'bmp'){
Res = Canvas2Image.saveAsBMP(oCanvas);
}
// if browser doesn't support mimetype alert user
if (!bRes) {
alert("Sorry, this browser is not capable of saving " + strType + " files!");
return false;
}
and on index.html, its look like this
<!-- export option (png, jpg, bmp) -->
<li>
<div class="btn-group dropup">
<a class="dropdown-toggle export btn" data-toggle="dropdown" href="#">
Export
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>
<a href="#" class="exportas" data-type='png'>PNG</a>
<a href="#" class="exportas" data-type='jpg'>JPG</a>
<a href="#" class="exportas" data-type='bmp'>BMP</a>
</li>
so what i wanna ask you is, how to make a code to send the image to form (form is on another pages) with details i have been mentioned above. thanks

Related

Convert html to Image and Download

I would like to convert every message that is received into an image, and with the download button download it. every post is different
This is my .js code
// fetch Messages
function fetchData() {
$('#displayMessages').html('<div class="alert alert-info">Stiamo recuperando i tuoi messaggi!...</div>');
$('#messages').click();
$.ajax({
url: 'controller/fetch_comments.php',
//success
success: function(data){
if (data=='please login') {
window.location='./';
console.log(data);
}
else{
var $fetch ='';
var component ='';
if (/^[\],:{}\s]*$/.test(data.replace(/\\["\\\/bfnrtu]/g, '#').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
data=JSON.parse(data);
console.log(data);
$.each(data, function(i, fetchAll){
var fetchData= data[i];
let message_title = fetchData.message_title ?? ""
$fetch += '<div class="row m-0"> <div class="pull-left alert col-md-2 mb-0"><img src="assets/img/anon.jpg" style=" width: 50px; height: 50px; border-radius:50%; box-shadow: 0 3px 2px rgba(0, 0, 0, 0.3); border: 5px solid #2c2c2c;" class="m-0"></div> <div class="alert col-md-7 m-0" style="margin-left:0px; color:#2c2c2c;"> <b>' +message_title +'</b><br>' +fetchData.description
+'</div> <div class="col-md-3 alert pull-right m-0"><span style="color: black;" class="fa fa-clock m-0"></span><br><text style="color: black; font-size:10px;"> ';
$fetch+=fetchData.date_created+'</text></div></div>';
});
} else {
$fetch +='<div class="alert alert-danger">Ancora nessun messaggio 😒</div>';
console.log(fetch);
$('#displayMessages').html($fetch)
}
$('#displayMessages').html($fetch);
}
}
});
}
this is the php code
$usersObj = new Comments();
$logsObj = new Logs();
$id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 1;
if (empty($id)) {
exit();
}
if ($allComments = $usersObj ->FETCH_COMMENTS($id)) {
$logDescription = 'data fetched!';
$logsObj->INSERT_LOG($id, $logDescription);
}else{
echo 'log failed';
}
echo isset($allComments) ? json_encode($allComments) : 'nothing found';
This is my html in my dashboard, is used to show the message
<div class="tab-pane active" id="home" role="tabpanel">
<div id="displayMessages">
</div>
</div>
I don't understand where I have to act, thanks for the help feel free to edit the code
You could do this as a oneliner in javascript.
Just by using the library html2canvas.
e.g.
html:
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
</div>
js:
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});
put the image into an a tag with the propertie of "download".
I hope i could help you out.
EDIT:
In your html file add the cdn as following to the head:
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas
/1.4.1/html2canvas.min.js"></script>
then in your js file
const body = document.querySelector("body");
const a_tag = document.createElement("a"); //just create an a tag
a_tag.innerHTML = "download"; //this text is displayed
a_tag.download = "image.png"; //pictures will download as image.png - you can customize the name and file format, but not all formats are acceptet in html2canvas
body.appendChild(a_tag); //append the a tag to the body element, you will need to customize this for your needs
html2canvas(document.querySelector(".wrapper")).then((canvas) => {
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob); //creates location of image
a_tag.href = url; //append url to a tags href
});
});
You will need this for every Message you receive. After your messages are displayed in the dom as html, the "html2canvas" will create an image out of that. In the "toBlob" function the image is just cached but not showing anywhere. We link the blob url (location of the cached image) to the a tags href. So if we then click on it, it will download. The .wrapper in the html2canvas function i've selected should be your message-div

How to add image into the specific section of the achor tag in javascript?

I have three images and two anchor tags. When user click on any link then user can select any image.Then this image must be replaced with anchor tag image in which user clicked.
var control3 = document.getElementById('control1').src;
var control4 = document.getElementById('control2').src;
function getImage(e) {
fullpath = e.children[0].src;
var filename = fullpath.replace(/^.*[\\\/]/, '');
var imageSrc = filename.split("\.")[0] + ".png";
if (control1 !== fullpath) {
document.getElementById('control1').src = "images/" + imageSrc;
}
if (control2 !== fullpath) {
document.getElementById('control2').src = "images/" + imageSrc;
}
if (control3 !== fullpath) {
document.getElementById('control3').src = "images/" + imageSrc;
}
}
<img onclick="getImage(this);" src="images/image1.png" alt="">
<img onclick="getImage(this);" src="images/image2.png" alt="">
<img onclick="getImage(this);" src="images/image3.png" alt="">
<img id="control1" src="">
<img id="control2" src="">
You've really only implemented part of the process here. You need to consider the flow of the program more carefully:
You need firstly to handle click events on the links.
And you also need to make it possible for users to click on an image to select it for replacement.
Then your code needs to be able to match the clicked image to the clicked link, so it knows what change to make.
N.B. in this demo I've replaced your inline event handlers with unobtrusive event handlers using addEventListener (i.e. declared in the JS, not embedded in the HTML).
//variables to hold program state
var selectEnabled = false;
var selectedImage = "";
//handle clicks on links
var links = document.querySelectorAll(".imageLink");
links.forEach(function(lnk) {
lnk.addEventListener("click", enableImageSelection);
});
function enableImageSelection(e) {
e.preventDefault(); //stop the hyperlink doing its normal job (i.e. moving to another page)
selectEnabled = true;
alert("Please select an image to replace");
imageSrc = this.querySelector("img").src;
}
//handle clicks on the replaceable images
var clickableImages = document.querySelectorAll(".clickableImage");
clickableImages.forEach(function(img) {
img.addEventListener("click", loadImage);
});
function loadImage() {
if (selectEnabled == true) {
console.log("replacing " + this.src + " with " + imageSrc);
this.src = imageSrc;
selectEnabled = false; //image is not clickable again until a link is clicked first.
}
}
<img class="clickableImage" src="images/image1.png" alt="1" />
<img class="clickableImage" src="images/image2.png" alt="2" />
<img class="clickableImage" src="images/image3.png" alt="3" />
<br/><br/>
<img src="images/image4.png"> Click me
<img src="images/image5.png"> Click me
I don't fully understand what you want from your explanation but I guess it's something like this:
Have lots of images and two empty "boxes".
Click on a box and you can click on an image.
The box will update when you clicked on the image.
optional: make it dynamic, so you can add any amount of images or "boxes".
In order to do so you need to:
Know what box you first clicked on.
Tell the images you can select between that they can be clicked.
Update the original box with the clicked image.
bonus: give the user feedback (highlights).
var selectedImageId = ""; // 1. Know what box you first clicked on.
const SELECTABLE_CLASS_NAME = 'selectable';
// 1. Know what box you first clicked on.
function selectImage(imageElement) {
let selectableImagesContanier = document.getElementById('selectables');
if (selectedImageId && selectedImageId != imageElement.id) {
let prevSelectedImage = document.getElementById(selectedImageId);
prevSelectedImage.classList.remove(SELECTABLE_CLASS_NAME);
}
selectedImageId = imageElement.id;
// 4. bonus: give the user feedback (highlights)
imageElement.classList.add(SELECTABLE_CLASS_NAME);
selectableImagesContanier.classList.add(SELECTABLE_CLASS_NAME);}
function getImage(imageElement) {
let selectableImagesContanier = document.getElementById('selectables');
// 2. Tell the images you can select between that they can be clicked.
if (selectableImagesContanier.classList.contains(SELECTABLE_CLASS_NAME)) {
let imageToBeUpdated = document.getElementById(selectedImageId);
// 3. Update the box with the clicked image.
imageToBeUpdated.src = imageElement.src;
// 4. bonus: give the user feedback (highlights)
selectableImagesContanier.classList.remove(SELECTABLE_CLASS_NAME);
imageToBeUpdated.classList.remove(SELECTABLE_CLASS_NAME);
imageToBeUpdated.classList.add('image-shown');
}
}
img {
width: 50px;
height: 50px;
border: 2px solid;
border-color: transparent;
}
#selectables.selectable > img,
img.selectable {
border-color: lightblue;
cursor: pointer;
}
.selected-image-container {
margin-top: 1rem;
}
.selected-image-container > img {
cursor: pointer;
background-color: lightgrey;
}
.selected-image-container > img.image-shown {
background-color: transparent;
}
<div id="selectables">
<img onclick="getImage(this)" src="https://picsum.photos/id/21/50/50" alt="">
<img onclick="getImage(this)" src="https://picsum.photos/id/31/50/50" alt="">
<img onclick="getImage(this)" src="https://picsum.photos/id/41/50/50" alt="">
</div>
<div class="selected-image-container">
<img id="control1" src="" onclick="selectImage(this)">
<img id="control2" src="" onclick="selectImage(this)">
</div>

How i make PHP/HTML images show original size onclick?

I am developing a news section that contains text and images in which the images to be clicked have to show their original size. Can someone help me with this?
<?php
$select_stmt=$db->prepare("SELECT * FROM teste ORDER BY id DESC;" ); //sql select query
$select_stmt->execute();
while($row=$select_stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="container" id="fadein">
<div class="row">
<div class="col-sm-4">
<div id="imagem"><img src="upload/<?php echo $row['image']; ?>" class="imagem"></div>
<script src="scripts/javascript.js"></script>
</div>
<div class="col-sm-8">
<div class="col-sm-12" id="titulo"><?php echo $row['titulo'];?></div>
<br>
<div class="col-sm-12" id="sub_titulo"><?php echo $row['sub_titulo'];?></div>
<br>
<div class="col-sm-12" id="texto"><?php echo $row['texto'];?></div>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-6" align="right">Editar</div>
<div class="col-sm-6">Eliminar</div>
</div>
<br>
<br>
<br>
<p class="barra"></p>
<br>
<br>
</div>
<?php
}
?>
(Probably second part is more usefull for your use case)
If you want pure javascript, you can set a onclick event listener and get images real size (Determine original size of image cross browser?) and set this size to image. (if you want it to set to old sizes on second click, save old size to a global variable and get then set). Which will look like this:
I'm not good with pure javascript but i guess this is it.
Add this code somewhere in your file. It will run for every image
<script>
window.onload = function() {
images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++){
images[i].onclick = function(e){
var isBig = e.target.getAttribute('isBig');
if (isBig === undefined || isBig == 'false'){
// make it big
e.target.setAttribute('isBig', 'true');
e.target.setAttribute('oldWidth', e.target.offsetWidth);
e.target.setAttribute('oldHeight', e.target.offsetWidth);
var newImg = new Image();
newImg.onload = function() {
e.target.style.width = newImg.width+"px";
e.target.style.height = newImg.height+"px";
}
newImg.src = e.target.getAttribute('src');
}
else {
// make it small
e.target.setAttribute('isBig', 'false');
e.target.style.width = e.target.getAttribute('oldWidth')+"px";
e.target.style.height = e.target.getAttribute('oldHeight')+"px";
}
}
}
}
</script>
This will set images width and height to original sizes.
If you want to make it fullscreen with absolute positioning, you need to create a new element and img tag. And you just need to set its src to image's src. Then you can show that image. Example:
<!-- add this somewhere in body -->
<!-- container -->
<div id="bigImage" style="z-index: 4; position: fixed; width: 100%; height: 100%; top: 0; left: 0; visibility: hidden;">
<!-- background. not necessary but usefull for close thing. -->
<div style="position: absolute; width: 100%; height: 100%; top: 0; left: 0; background: rgba(0, 0, 0, .7); cursor: pointer;" onclick="closeImage()"></div>
<!-- image element. object-fit: contain; for full window size -->
<img src="<?php echo $row['image']; ?>" alt="bigImage" id="bigImageChild" style="position: absolute; top: 5%; left: 5%; z-index: 6; width: 90%; height: 90%; object-fit: contain;">
<!-- close button -->
<span onclick="closeImage()" style="position: absolute; right: 20px; top: 20px; font-weight: 900; color: white; cursor: pointer;">X</span>
</div>
<!-- script for image -->
<script>
function closeImage() {
document.getElementById("bigImage").style.visibility = 'hidden';
}
images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++){
// on image click
images[i].onclick = function(e){
// set image src
document.getElementById("bigImageChild").src = e.target.src;
// show image
document.getElementById("bigImage").style.visibility = 'visible';
}
}
</script>
I need to set the image on is original size when i click on the first time and the second click to the image go back to is original size defined in the html.

Change Image every 20 seconds Javascript with Rows

I found this code from here but I need to add these things in this javascript.
Fade Effect
Want to show images with 2 rows, means I will add 10 images. 5 Images will show on 1st row and 5 images will show in 2nd row.
Want to add Text for every picture e.g. Name and Price
Mouse over image changing stop
<script>
var links = [
"abc.org",
"def.org",
"ghi.org",
"ghi33.org"
];
var images = [
"https://dmcfebaedy6rh.cloudfront.net/product/front/white/spl5596.360x180.1443167798.jpg",
"https://dmcfebaedy6rh.cloudfront.net/product/front/white/mt6050.360x180.1430798334.jpg",
"https://dmcfebaedy6rh.cloudfront.net/product/front/white/pl5087.360x180.1423189940.jpg",
"https://dmcfebaedy6rh.cloudfront.net/product/front/white/spl5596.360x180.1443167798.jpg"
];
var i = 0;
var renew = setInterval(function(){
if(links.length == i){
i = 0;
}
else {
document.getElementById("bannerImage").src = images[i];
document.getElementById("bannerLink").href = links[i];
i++;
}
},10000);
</script>
<a id="bannerLink" href="abc.org" onclick="void window.open(this.href); return false;">
<img id="bannerImage" src="https://d37j5ujucg66b1.cloudfront.net/product/front/white/pl5393.360x180.1456885745.jpg">
</a>
The problem with a question like this is, we have no idea what you're really aiming for. What we need from you is a little bit of code so we can see where you're heading.
I'm sure any number of us could throw together a little carousel that works, but that's not really what this site is for. It's to help people learn and work out what they did wrong or what they need to do to solve a problem.
That being said it would feel wrong of me to write all this without presenting some code.
var caraSel = document.querySelector(".simple-image");
var imageSel = document.querySelectorAll(".bannerLink");
var imageSelMax = imageSel.length - 1;
var imageInt = 0;
var imageIntNext = 1;
var renew = setInterval(function() {
imageSel[imageInt].classList.add("hidden");
imageSel[imageIntNext].classList.remove("hidden");
imageSelMax === imageInt ? imageInt = 0 : ++imageInt;
imageSelMax === imageIntNext ? imageIntNext = 0 : ++imageIntNext;
}, 1000);
caraSel.addEventListener("mouseover", function() {
clearInterval(renew);
});
caraSel.addEventListener("mouseout", function() {
renew = setInterval(function() {
imageSel[imageInt].classList.add("hidden");
imageSel[imageIntNext].classList.remove("hidden");
imageSelMax === imageInt ? imageInt = 0 : ++imageInt;
imageSelMax === imageIntNext ? imageIntNext = 0 : ++imageIntNext;
}, 1000);
});
.simple-image {
position: relative;
width: 360px;
height: 180px;
}
.bannerLink {
position: fixed;
background: #FFF;
top: 0;
left: 0;
will-change: opacity;
transition: opacity .6s ease-in;
text-decoration: none;
color: #000;
}
.bannerLink.hidden {
opacity: 0;
}
<div class="simple-image">
<a class="bannerLink" href="abc.org" onclick="void window.open(this.href); return false;">
<img class="bannerImage" src="https://d37j5ujucg66b1.cloudfront.net/product/front/white/pl5393.360x180.1456885745.jpg">#1
</a>
<a class="bannerLink hidden" href="def.org" onclick="void window.open(this.href); return false;">
<img class="bannerImage" src="https://dmcfebaedy6rh.cloudfront.net/product/front/white/mt6050.360x180.1430798334.jpg">#2
</a>
<a class="bannerLink hidden" href="ghi.org" onclick="void window.open(this.href); return false;">
<img class="bannerImage" src="https://dmcfebaedy6rh.cloudfront.net/product/front/white/pl5087.360x180.1423189940.jpg">#3
</a>
<a class="bannerLink hidden" href="ghi33.org" onclick="void window.open(this.href); return false;">
<img class="bannerImage" src="https://dmcfebaedy6rh.cloudfront.net/product/front/white/spl5596.360x180.1443167798.jpg">#4
</a>
</div>
Sped up of course be you get the idea.

JavaScript file not working in browser, however it does work in codepen

I am building a webpage that uses a JavaScript application called photo swipe (http://photoswipe.com/).
I cannot get the JavaScript to run in my browser locally.
I have tested this in several different browsers. I have double checked all file names (including capitalization) and locations as referenced in the code. All the files are stored on my computer in the same folder, in the correct format. I have tried clearing the cache. The external libraries required to run the JavaScript are referenced in the files as they are in Code Pen.
It works in Code Pen just fine like so:
http://codepen.io/anon/pen/XJEWEN
Here are the files I am trying to run on the browser locally:
HTML
<!DOCTYPE html>
<html>
<head>
<!-- Core JS file -->
<script src="http://photoswipe.s3-eu-west-1.amazonaws.com/pswp/dist/photoswipe.min.js"></script>
<!-- UI JS file -->
<script src="http://photoswipe.s3-eu-west-1.amazonaws.com/pswp/dist/photoswipe-ui-default.min.js"></script>
<!-- Link to JS document as it is in code-pen, on computer stored in same folder as HTML document-->
<script type="text/javascript" src="document.js"></script>
<!-- Link to main css document as it is in code-pen, on computer stored in same folder as HTML document-->
<link type="text/css" rel="stylesheet" href="main.css"/>
<!-- Core CSS file -->
<link rel="stylesheet" href="http://photoswipe.s3.amazonaws.com/pswp/dist/photoswipe.css"/>
<!-- Skin CSS file (styling of UI - buttons, caption, etc.)
In the folder of skin CSS file there are also:
- .png and .svg icons sprite,
- preloader.gif (for browsers that do not support CSS animations) -->
<link rel="stylesheet" href="http://photoswipe.s3.amazonaws.com/pswp/dist/default-skin/default-skin.css"/>
<meta charset="UTF-8">
<meta name="keywords" content="Photo, Web Design">
<meta name="description" content="Examples of ways that photos can be presented online">
<html lang="en-US">
</head>
<body>
<h2>Gallery 1</h2>
<div class="my-simple-gallery" itemscope itemtype="http://schema.org/ImageGallery">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" itemprop="contentUrl" data-size="964x1024">
<img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2.1</figcaption>
</figure>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" itemprop="contentUrl" data-size="1024x683">
<img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2.2</figcaption>
</figure>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_b.jpg" itemprop="contentUrl" data-size="1024x768">
<img src="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_m.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2.3</figcaption>
</figure>
</div>
<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<!-- Background of PhotoSwipe.
It's a separate element, as animating opacity is faster than rgba(). -->
<div class="pswp__bg"></div>
<!-- Slides wrapper with overflow:hidden. -->
<div class="pswp__scroll-wrap">
<!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
<!-- don't modify these 3 pswp__item elements, data is added later on. -->
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<!-- Controls are self-explanatory. Order can be changed. -->
<div class="pswp__counter"></div>
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title="Share"> </button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
<!-- element will get class pswp__preloader--active when preloader is running -->
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class="pswp__share-tooltip"></div>
</div>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class="pswp__caption">
<div class="pswp__caption__center"></div>
</div>
</div>
</div>
</section>
</div>
</div>
</body>
</html>
CSS
.my-simple-gallery {
width: 100%;
float: left;
}
.my-simple-gallery img {
width: 100%;
height: auto;
}
.my-simple-gallery figure {
display: block;
float: left;
margin: 0 5px 5px 0;
width: 150px;
}
.my-simple-gallery figcaption {
display: none;
}
*{margin:0;}
.my-simple-gallery {
width: 100%;
float: left;
}
.my-simple-gallery img {
width: 100%;
height: auto;
}
.my-simple-gallery figure {
display: block;
float: left;
margin: 0 5px 5px 0;
width: 150px;
}
.my-simple-gallery figcaption {
display: none;
}
JavaScript
var initPhotoSwipeFromDOM = function(gallerySelector) {
// parse slide data (url, title, size ...) from DOM elements
// (children of gallerySelector)
var parseThumbnailElements = function(el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
figureEl,
childElements,
linkEl,
size,
item;
for(var i = 0; i < numNodes; i++) {
figureEl = thumbElements[i]; // <figure> element
// include only element nodes
if(figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0]; // <a> element
size = linkEl.getAttribute('data-size').split('x');
// create slide object
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
if(figureEl.children.length > 1) {
// <figcaption> content
item.title = figureEl.children[1].innerHTML;
}
if(linkEl.children.length > 0) {
// <img> thumbnail element, retrieving thumbnail url
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl; // save link to element for getThumbBoundsFn
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};
// triggers when user clicks on thumbnail
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
var clickedListItem = closest(eTarget, function(el) {
return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
});
if(!clickedListItem) {
return;
}
// find index of clicked item
var clickedGallery = clickedListItem.parentNode,
childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = 0,
index;
for (var i = 0; i < numChildNodes; i++) {
if(childNodes[i].nodeType !== 1) {
continue;
}
if(childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if(index >= 0) {
openPhotoSwipe( index, clickedGallery );
}
return false;
};
// parse picture index and gallery index from URL (#&pid=1&gid=2)
var photoswipeParseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if(hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if(params.gid) {
params.gid = parseInt(params.gid, 10);
}
if(!params.hasOwnProperty('pid')) {
return params;
}
params.pid = parseInt(params.pid, 10);
return params;
};
var openPhotoSwipe = function(index, galleryElement, disableAnimation) {
var pswpElement = document.querySelectorAll('.pswp')[0],
gallery,
options,
items;
items = parseThumbnailElements(galleryElement);
// define options (if needed)
options = {
index: index,
// define gallery index (for URL)
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function(index) {
// See Options -> getThumbBoundsFn section of docs for more info
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
},
// history & focus options are disabled on CodePen
// remove these lines in real life:
history: false,
focus: false
};
if(disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
// loop through all gallery elements and bind events
var galleryElements = document.querySelectorAll( gallerySelector );
for(var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i+1);
galleryElements[i].onclick = onThumbnailsClick;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid > 0 && hashData.gid > 0) {
openPhotoSwipe( hashData.pid - 1 , galleryElements[ hashData.gid - 1 ], true );
}
};
// execute above function
initPhotoSwipeFromDOM('.my-simple-gallery');
I am stumped. Would really appreciate some guidance to get it working in browser. Thanks in advance. :)
The problem is with when you call the function. You are trying to find the elements before they are rendered to the page. You can call the function at the end of the html document:
<script>
initPhotoSwipeFromDOM('.my-simple-gallery');
</script>
Another way to do it is to add to the onload on body tag:
<body onload="initPhotoSwipeFromDOM('.my-simple-gallery')">
Or set it to the onload function on window:
window.onload="initPhotoSwipeFromDOM('.my-simple-gallery');";
You need to add the link to the js library which i don't see.
<script src="https://code.jquery.com/jquery.min.js"></script>
Maybe i missed it though.

Categories

Resources