How do I make this code run multiple drag and drop?
I know that in jquery it uses 'each function', but I don't know how to do that in js. I need the selector to become a class so it can use more than 1 object, not only 1 id. I got the tutorial from this site and already changed the
document.getElementById("example");
to
document.getElementsByClassName("example");
However, I haven't yet succeeded due to this >
Uncaught TypeError: droparea.addEventListener is not a function
Any suggestions?
DRAG AND DROP IMAGE
FIDDLE HERE >>
<div class="container">
<div class="row">
<div class="col-xs-2 left">
<div class="filedroparea">(Drag & drop file here)</div>
<img class="previewimage" alt="Preview Image" />
</div>
<!-- .left -->
<div class="col-xs-8 center">
<div class="box-wrap">
<div class="box-ads-1">
<div class="filedroparea">(Drag & drop file here)</div>
<img class="previewimage" alt="Preview Image" />
</div>
<div class="box-ads-2">
<div class="filedroparea">(Drag & drop file here)</div>
<img class="previewimage" alt="Preview Image" />
</div>
</div>
</div>
<!-- .center -->
<div class="col-xs-2 right">
<div class="filedroparea">(Drag & drop file here)</div>
<img class="previewimage" alt="Preview Image" />
</div>
<!-- .right -->
</div>
<!-- .row -->
</div>
<!-- .container -->
if (window.FileReader) {
// Current browser supports drag and drop
var droparea = document.getElementsByClassName("filedroparea");
droparea.addEventListener("dragenter", dragenter, false);
droparea.addEventListener("dragover", dragover, false);
droparea.addEventListener("drop", drop, false);
var showButton = document.getElementsByClassName("showdroparea");
showButton.addEventListener("click", showarea, false);
} else {
document.getElementsByClassName('filedroparea').innerHTML = 'Your browser does not support FileReader HTML5 API';
}
// Event callback functions
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
// Get list of dropped files
var dt = e.dataTransfer;
var images = dt.files;
// Reading first file
var image = images[0];
var reader = new FileReader();
reader.readAsDataURL(image);
reader.addEventListener("loadend", showPreview, false);
}
function showPreview(e, file) {
var imageElement = document.getElementsByClassName('previewimage');
imageElement.src = this.result;
document.getElementsByClassName("filedroparea").style.display = 'none';
imageElement.style.display = 'block';
document.getElementsByClassName("showdroparea").style.display = 'block';
}
function showarea(e) {
document.getElementsByClassName("filedroparea").style.display = 'block';
document.getElementsByClassName('previewimage').style.display = 'none';
document.getElementsByClassName("showdroparea").style.display = 'none';
}
.filedroparea {
width: 100%;
height: 100%;
text-align: center;
background: #ccc;
}
.previewimage {
display:none;
}
.showdroparea {
display:none;
cursor: pointer;
}
Related
Here when the user selects the images it gets append inside the ul tag. This all are working fine(There still might be some problems in the code below since I am very beginner in jquery).
Now what I want to change here is, the image which gets selected at first will have a <li class='thumbnail'> by default then other remaining selected images will not have this thumbnail class in the li tag. But the user later on can change the thumbnail image by clicking the image. How can I do it here ?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
img = `
<li class="thumbnail">
<div class="image">
<img src="${e.target.result}" width="83" height="100"/>
<div class="close"><div class="ic-close" id="img-remove"></div>
</div>
<p>Thumbnail</p></li>
`
$('#blah').append(img);
if ( $('ul#blah li').length > 5 ) {
$("#blah li:last-child").remove();
alert("You can't upload more than 5 images.");
}
}
reader.readAsDataURL(input.files[0]);
$('ul#blah').on('click','.ic-close',function(e) {
console.log('k');
$(this).closest('li').remove();
});
}
}
$("#imgInp").change(function(){
readURL(this);
});
</script>
html
<div class="col-md-6 form-group">
<label for="">Upload Image</label>
<ul class="list list-inline" id="blah">
<div class="files--upload"><input name='image' class="d-none imgUpload" type="file"
id="imgInp" placeholder=""/><label class="upload-label" for="imgInp">
<div class="ic-add"></div>
<div class="mt-2">Add Photo</div>
</label></div>
</ul>
</div>
One of the simplest ways to download previews is with a fast counter, which will prohibit subsequent downloads to the preview.
I have declared globally a variable:
var prew = true;
Here there is a one-time addition of a image for the preview, and also, the prew is assigned a false, which means the impossibility of further adding a image to this div (#img_prew).
if(prew) {
$('#img_prew').append(img);
$('#img_prew').find('.thumbnail .image p').text('This is a preview');
prew = false;
}
Created div for preview:
<div id="img_prew">...</div>
And at the end I set the width and height through css:
#img_prew img{
width: 300px;
height: 300px;
}
var prew = true;
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
img = `
<li class="thumbnail">
<div class="image">
<img src="${e.target.result}" width="83" height="100"/>
<div class="close"><div class="ic-close" id="img-remove"></div>
</div>
<p>Thumbnail</p></li>
`
if(prew) {
$('#img_prew').append(img);
$('#img_prew').find('.thumbnail .image p').text('This is a preview');
prew = false;
}
$('#blah').append(img);
if ( $('ul#blah li').length > 5 ) {
$("#blah li:last-child").remove();
alert("You can't upload more than 5 images.");
}
}
reader.readAsDataURL(input.files[0]);
$('ul#blah').on('click','.ic-close',function(e) {
console.log('k');
$(this).closest('li').remove();
});
}
}
$("#imgInp").change(function(){
readURL(this);
});
#img_prew img{
width: 300px;
height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.17.0/jquery.validate.js"></script>
<div class="col-md-6 form-group">
<label for="">Upload Image</label>
<div id="img_prew"></div>
<ul class="list list-inline" id="blah">
<div class="files--upload"><input name='image' class="d-none imgUpload" type="file"
id="imgInp" placeholder=""/><label class="upload-label" for="imgInp">
<div class="ic-add"></div>
<div class="mt-2">Add Photo</div>
</label></div>
</ul>
</div>
I'm trying to upload a second img to the cropper that populates the second .img-result. The cropper should populae whatever was uploaded, and then when the save btn is pressed, the .img-result is updated.
I added the attribute data-up but I'm not sure how to call it in the JS.
// vars
var result = document.querySelector('.result'),
img_result = document.querySelector('.img-result'),
img_w = document.querySelector('.img-w'),
img_h = document.querySelector('.img-h'),
options = document.querySelector('.options'),
save = document.querySelector('.save'),
cropped = document.querySelector('.cropped'),
upload = document.querySelector('.file'),
cropper = '';
// on change show image with crop options
upload.addEventListener('change', function(e) {
if (e.target.files.length) {
// start file reader
var reader = new FileReader();
reader.onload = function(e) {
if (e.target.result) {
// create new image
var img = document.createElement('img');
img.id = 'image';
img.src = e.target.result;
// clean result before
result.innerHTML = '';
// append new image
result.appendChild(img);
// init cropper
cropper = new Cropper(img);
}
};
reader.readAsDataURL(e.target.files[0]);
}
});
// save on click
save.addEventListener('click', function(e) {
e.preventDefault();
// get result to data uri
var imgSrc = cropper.getCroppedCanvas({
width: img_w.value // input value
}).toDataURL();
// show image cropped
cropped.src = imgSrc;
});
.img-result {
border: 2px solid;
width: 50px;
height: 50px;
}
.img-result img {
max-height: 100%;
max-width: 100%;
}
.page {
display: flex;
align-items: flex-start;
flex-wrap: wrap;
height: 100%;
}
.result {
display: flex;
}
.box {
padding: 0.5em;
width: 100%;
margin: 0.5em;
}
.box-2 {
padding: 0.5em;
width: calc(100%/2 - 1em);
}
.img-w {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main class="page">
<div class="box">
<div class="options">
<input type="number" class="img-w" value="300" min="100" max="1200" />
</div>
<button class="btn save">Save</button>
</div>
<div class="box">
<input class="file" type="file" id="file-input" data-up="1">
</div>
<div class="box">
<input class="file" type="file" id="file-input" data-up="2">
</div>
<div class="box-2">
<div class="result"></div>
</div>
<div class="result">
<div class="box-2 img-result">
<img class="cropped" src="" alt="" data-up="1">
</div>
<div class="box-2 img-result">
<img class="cropped" src="" alt="" data-up="2">
</div>
</div>
</main>
First of all, as I mentioned in comments. Id must be for each element of your DOM. So, you better change id="file-input" to id="file-input1" and so on.
And It looks like you want to get the attribute value data-up when save function called,
You can do that in this way
save.addEventListener('click', function(e) {
e.preventDefault();
// get result to data uri
document.getElementById('file-input1).getAttribute('data-up')
....
I'm trying to make a expandable h3. For that I'll have a "plus" image to click and when it's clicked has to change to a "minus" image and I need to add a css class to the h3 to show the content. I'll paste all the code below:
<div class="default">
[ManageBlog]
<div class="msearch-result" id="LBSearchResult[moduleid]" style="display: none">
</div>
<div class="head">
<h1 class="blogname">
[BlogName] <img src="/portals/40/Images/Train_Fitness_2015_S/images/plus_symbol.png" alt="Plus Button" id="ExpandBlogDescriptionImg"></h1> [RssFeeds]
<br style="line-height: 12px; clear: both" />
<h3 class="blogdescription">
[BlogDescription]</h3> [Author]
</div>
<br /> [Posts] [Pager]
</div>
<div style="clear: both"></div>
And here is the javascript:
jQuery(document).ready(function() {
$("#ExpandBlogDescriptionImg").click(function() {
var right = "https://train.fitness/portals/40/Images/Train_Fitness_2015_S/images/plus_symbol.png";
var left = "https://train.fitness/portals/40/Images/Train_Fitness_2015_S/images/minus_symbol.png";
element.src = element.bln ? right : left;
element.bln = !element.bln;
});
var img = $("#ExpandBlogDescriptionImg");
if (img.src = "https://train.fitness/portals/40/Images/Train_Fitness_2015_S/images/minus_symbol.png") {
$('.blogdescription').addClass("ExpandBlogDescriptionText");
} else {
$('.blogdescription').removeClass("ExpandBlogDescriptionText");
};
});
you can use .attr function of jquery to set image source like
$('.img-selector').attr('src','plusorminusimagepath.jpg');
and you can have a boolean flag to know if it is less or more
Here i was changing alt attribute of image tag on click. the same way you can change src
jQuery(document).ready(function() {
$("#ExpandBlogDescriptionImg").click(function() {
if ($(this).attr("alt") == "+") {
$(this).attr("alt", "-");
} else {
$(this).attr("alt", "+");
}
});
var img = $("#ExpandBlogDescriptionImg");
if (img.src = "https://train.fitness/portals/40/Images/Train_Fitness_2015_S/images/minus_symbol.png") {
$('.blogdescription').addClass("ExpandBlogDescriptionText");
} else {
$('.blogdescription').removeClass("ExpandBlogDescriptionText");
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="default">
[ManageBlog]
<div class="msearch-result" id="LBSearchResult[moduleid]" style="display: none">
</div>
<div class="head">
<h1 class="blogname">
[BlogName] <img alt="+" src="/portals/40/Images/Train_Fitness_2015_S/images/plus_symbol.png" alt="Plus Button" id="ExpandBlogDescriptionImg"></h1> [RssFeeds]
<br style="line-height: 12px; clear: both" />
<h3 class="blogdescription">
[BlogDescription]</h3> [Author]
</div>
<br />[Posts] [Pager]
</div>
<div style="clear: both"></div>
You should use a sprite image and CSS, else when you click and it will load another image, for some time between image would disappear.
HTML
<div class="head">
<h1 class="blogname">
[BlogName] <span class="plus icon"></span></h1>
[RssFeeds]
<br style="line-height: 12px; clear: both" />
<h3 class="blogdescription">
[BlogDescription]</h3>
[Author]</div>
<br />
CSS
.icon{
width:30px;
height:30px;
display:inline-block;
background-image:url(plus-minus-sprite-image.png);
}
.icon.plus{
background-position:20px center;
}
.icon.minus{
background-position:40px center;
}
JS
$('.icon').click(function(){
$(this).toggleClass("plus minus");
if($(this).hasClass("plus")){
$('.blogdescription').addClass("ExpandBlogDescriptionText");
}else{
$('.blogdescription').removeClass("ExpandBlogDescriptionText");
}
// Or $('.blogdescription').toggleClass("ExpandBlogDescriptionText");
});
$("#ExpandBlogDescriptionImg").click( function(e){
var right = "https://train.fitness/portals/40/Images/Train_Fitness_2015_S/images/plus_symbol.png";
var left = "https://train.fitness/portals/40/Images/Train_Fitness_2015_S/images/minus_symbol.png";
if($(e.currentTarget).attr('img') == left){
$(this).hide();
$(e.currentTarget).attr('img',right);
}else{
$(this).show();
$(e.currentTarget).attr('img',left);
}
});
I am trying to show images on a link click and hiding that image if clicked outside. After trying so many solutions for this I have came up with like below code.
<script>
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
</script>
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center" onclick="javascript:setImageVisible('popup1', false)">
<div id="Btn7"></div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
</div>
The above code is working fine. But when I add other image like below, its not working. When I clicked outside then images are not hiding.
<script>
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
$(document).click(function() {
var img1 = document.getElementById('popup1');
var img2 = document.getElementById('popup2');
img1.style.visibility = 'hidden';
img2.style.visibility = 'hidden';
});
</script>
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center">
<div id="Btn7"></div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
<div id="Btn8"></div>
<img id="popup2" class="img_popup2" src="../screenshots/pop-up2.png" style="visibility:hidden" />
</div>
Can anyone please suggest what should I do ?
You don't need jQuery to do this.
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
function hideAll() {
var img1 = document.getElementById('popup1');
var img2 = document.getElementById('popup2');
img1.style.visibility = 'hidden';
img2.style.visibility = 'hidden';
}
function click(e) {
e.stopImmediatePropagation();
var id, el = this;
while (el) {
el = el.nextSibling;
if (el.nodeName === 'IMG') { // finds the next sibling img element
id = el.id;
el = null;
}
}
hideAll(); // hide all images
setImageVisible(id, true); // show the right one
};
document.addEventListener('click', hideAll);
var btns = document.querySelectorAll('.btn'),
i = 0,
len = btns.length;
for (; i < len; i++) {
btns[i].addEventListener('click', click);
}
img {
width: 100px;
height: 100px;
border: 1px solid black;
}
<div id="wrapper" style="margin-top: -5px; text-align:center" align="center">
<div class="btn" id="Btn7">Image 1</div>
<img id="popup1" class="img_popup1" src="../screenshots/pop-up.png" style="visibility:hidden" />
<div class="btn" id="Btn8">Image 2</div>
<img id="popup2" class="img_popup2" src="../screenshots/pop-up2.png" style="visibility:hidden" />
</div>
Sure, as you have added a tag jquery, I am asking you to do it in a simple way like this:
Snippet:
$(function () {
$(".imgPreview").hide();
$(".unstyled li a").click(function () {
$(".imgPreview").show().find("img").attr("src", $(this).attr("href"));
return false;
});
$("body").click(function () {
$(".imgPreview").hide();
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;}
body {margin: 10px;}
li {margin: 5px;}
.unstyled, .imgPreview {float: left; width: 50%;}
.unstyled, .imgPreview img {max-width: 100%;}
p {margin: 5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>Click on a link to show the respective image. Click outside to hide it!</p>
<p>Also you can right click and open it to open the image in a new tab!</p>
<ul class="unstyled">
<li>350x150</li>
<li>750x150</li>
<li>350x150</li>
<li>100x100</li>
<li>350x150</li>
</ul>
<div class="imgPreview">
<img src="" alt="" />
</div>
Try this simple demo
<!DOCTYPE html>
<html>
<head>
<script src = "jquery-1.10.2.min.js"></script>
</head>
<body>
Click to show image
<img id="image" style="display:none;height:500px; width:500px;">
<script type="text/javascript">
$('#imageLink').click(function (e){
e.stopPropagation();
$('#image').show();
});
$('body').click(function () {
$('#image').hide();
})
</script>
</body>
</html>
Remove inline event handler and write for common click event ,
1) bind the click event for all a tag inside wrapper id and then show the images when link is clicked
2) bind the click event for document and hide the all images when clicking outside of link
$("#popup1,#popup2").hide();
$("#Btn7,#Btn8").click(function (e) {
e.stopPropagation();
$(this).next().show();
})
$(document).click(function () {
$("#popup1,#popup2").hide();
})
DEMO
$(document).ready(function () {
$("#linkbutton_id").click(function () {
alert("The paragraph was clicked.");
if($("#image").hide())
{
$("#image").show();
return false;
}
});
});
$(document).ready(function () {
$("#div_id").click(function(){
$("#image").hide();
});
});
Code plus output link
https://jsfiddle.net/umxrn0Lg/2/
fullscreen output link
https://jsfiddle.net/umxrn0Lg/3/embedded/result/
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.