Generate html using Javascript - javascript

I have a gallery page that is updated often with new images. I use simple HTML to post the photos. My process currently is copy and paste the set of tags for a photo and change the number to correspond with the image file name. E.G. I change the number 047 to 048. Copy-Paste, change it to 049. This goes on until I have reached the number of additional photos. As you can see, this is very inefficient and there must be a better way of doing this. I was wondering if there is a simpler way to achieve this with Javascript? Perhaps generate additional tags by inputing a certain number or range?
Any ideas that would make this process efficient are welcomed please! Thank you!
<div class="cbp-item trim">
<a href="../assets/images/trim/img-trim-047.jpg" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="../assets/images/trim/img-trim-047.jpg" alt="">
</div>
</a>
</div>

You could use a templating solution. There are several libraries for that, but you can also implement it yourself.
Here is one way to do that:
Put the HTML for one image in a script tag that has a non-standard language property so the browser will just ignore it
Put some keywords in there that you'll want to replace, e.g. {url}. You can invent your own syntax.
Read that template into a variable
In the JS code, put all the images' URLs in an array of strings
For each element in that array, replace the keywords in the template string with that particular URL, and concatenate all these resulting HTML snippets.
Inject the resulting HTML into the appropriate place in the document.
Here is a snippet doing that:
// Add new images here:
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/330px-SNice.svg.png",
"https://nettemarie357.files.wordpress.com/2014/09/smiley-face.jpg?w=74&h=74",
];
// Load the template HTML
var template = document.querySelector('script[language="text/template"]').innerHTML;
// Use template to insert all the images:
container.innerHTML = images.map(url => template.replace(/{url}/g, url)).join('');
img { max-width: 50px }
<div id="container"></div>
<script language="text/template">
<div class="cbp-item trim">
<a href="{url}" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="{url}" alt="">
</div>
</a>
</div>
</script>

This would help you creating it programatically:
var new_row = document.createElement('div');
new_row.className = "cbp-item trim";
var a = document.createElement('a');
a.href = "../assets/images/trim/img-trim-047.jpg";
a.className= "cbp-caption cbp-lightbox";
document.body.appendChild(a);
var div = document.createElement('div');
div.className = "cbp-caption-defaultWrap";
var img = document.createElement('img');
img.src= "../assets/images/trim/img-trim-047.jpg";
div.appendChild(img);
a.appendChild(div);
new_row.appendChild(a);

If it is just about printing HTML, I suggest you to use plugins like Emmet for Sublime Text editor.
When you install this plugin and see how it works, you can simple create a complex html in a way that 'for' loop would do this. This will help you to change only the image/link number of every item.
Check the demo in the link, that I added.

Here's an example in Java Script that will generate the html you will need. Set the total to whatever number you need to generate the number of images you want.
var total = 47;
var hook = document.getElementById('hook');
// Main Node for SlideShow
var node = document.createElement('div');
node.classList = "cbp-item trim";
// Work out the correct number
var n = function(int) {
var length = int.toString().length;
return length === 1
? '00' + int
: length === 2
? '0' + int
: length
}
// Create the item
var createItem = function(int){
// Create Anchor
var a = document.createElement('a');
a.href = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg" class="cbp-caption cbp-lightbox';
a.classList = 'cbp-caption cbp-lightbox';
// Create Div
var div = document.createElement('div');
div.classList = 'cbp-caption-defaultWrap';
// Create Image
var img = document.createElement('img');
img.src = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg';
img.alt = 'gallery image';
// Finalise Dom Node
var container = div.appendChild(img)
a.appendChild(div);
// Return Final Item
return a
}
// Create Items
for (var i = 1; i < total + 1; i++) {
node.appendChild(createItem(i));
}
// Append Main Node to Hook
hook.appendChild(node);
<div id="hook"></div>

Related

How to display an array of images as a list and make them clickable to display some text using javascript?

I need to display a list of images from an array and also make it clickable to display some text on click. Looking for some simple solution only with javascript.
var images = ["img1", "img2", "img3"];
var allPics = images.length;
var i = 0;
for(;i<allPics; i++){
myImg.src = images[i];
}
Example here:
https://jsfiddle.net/gmqLtd1u/1/
Now only one image is displayed.
Now only one image is displayed.
Because you're using one <img> and update its src several times in loop. After last iteration, its src is not updated anymore. That's why you see the last image.
Change your html, so that instead of <img> you have <div> as container/placeholder:
<!-- <img id="myImg"/> -->
<div id="myImg"></div>
And change your JS, to create <img> and append it to <div>:
for(;i<allPics; i++){
// myImg.src = images[i];
// TODO: adjust this to whatever you want
// in this example, use `<a>` that link to another page
// you can use javascript to show modal/alert too
var a = document.createElement('a');
a.href = 'example.html'; // TODO: adjust this
var img = document.createElement('img');
img.src = images[i];
a.appendChild(img);
document.getElementById('myImg').appendChild(a);
}
And maybe your CSS, to match with new output:
#myImg img {
...
}

Can you generate html locally, without using a server?

I'm trying to show images in a local html file using a loop. This is what I want it to show in the web browser:
<div id="polybridges">
<img src="polybridge_1.gif">
<img src="polybridge_2.gif">
<img src="polybridge_3.gif">
<img src="polybridge_4.gif">
<img src="polybridge_5.gif">
</div>
This is my attempt to do this with javascript:
<script>
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
</script>
<div id="polybridges">
This doesn't generate anything. Is there a way to show images in a loop without using a server / localhost?
At first your element must be defined before script execution (so change the order). I suppose you want to append elem (instead of "hallo" string):
<div id="polybridges"></div>
<script>
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
</script>
Put your images in the same directory as your html file.
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
And change the argument for appendChild.
As malix states in his comment, you should use document.getElementById("polybridges").appendChild(elem); instead of document.getElementById("polybridges").appendChild("hallo"); (so append the element instead of string "hallo").
And, as the rest states, the images should be where you tell the browser they are.
Yes you can display images without server, you have to have that images in same directory as your html file or in images folder which in same level as your html file ( for that case images would be available as <img src="images/polybridge_5.gif">
appendChild take Node as parameter (not string)
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
You need to take care of one thing. You are trying to get element by ID. So you need to make sure that html is valid. Provide proper close tag for the element. Also use the elem variable in the appendChild().
for (var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src = 'polybridge_' + i + '.gif';
console.log(elem)
document.getElementById("polybridges").appendChild(elem);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="polybridges"></div>

Dynamically change <div> background-image with javascript

I'm looking for some help writing a javascript snippet that will DYNAMICALLY update a div style= "background-image:url..." to match the a href above it. This is on a portfolio website, so this is a gallery where all the images are live at once. I need the snippet to run through each individual a href and nested div underneath it and have them match, unique to each image (Don't want a page of the same picture 20 times)
I'm just starting to learn JS, so I've been struggling with this one. Here's the html.
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
This href should from above should be copied to the div style url below.
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
This is what it looks like as a whole...
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
Any help would be greatly appreciated!
This is what I'm thinking, so far...
function abc() {
var a = document.getElementById("tobematched").
var b = document.getElementById("matcher").style.backgroundImage;
}
Not sure where to go from here, since I don't know how to grab the href... I think I'm on the right track.
You can use a combination of querySelector() and the .href property to get what you need:
var targetDiv = document.querySelector('#matcher');
var url = targetDiv.parentNode.href;
targetDiv.style.backgroundImage = 'url(' + url + ')';
Alternatively you can use:
var url = document.querySelector('#tobematched').href
This second option does not depend on the structure of the document, but causes JS to look through the whole document again.
If you were using jQuery:
var url = $('#tobematched')attr('href');
$('#matcher').css('background-image', 'url(' + url + ')');
Live Example
Edit: As per the further description by OP in the comments, here is the code you actually need:
var targetDivs = document.querySelectorAll('.img-container');
for (var i = 0; i < targetDivs.length; i++) {
var url = targetDivs[i].parentNode.href;
targetDivs[i].style.backgroundImage = 'url(' + url + ')';
}

modify the end of an image source from 's.jpg' to 'o.jpg' with javascript

My CMS has a plugin for pulling in facebook images with stories. I cannot change it.
In the source it creates the image URL ends in s.jpg but I would like to modify it so it ends in o.jpg in order to pull in the largest photo type
This is the code:
<div class="post_picture">
<img src="http://photos-g.ak.fbcdn.net/hphotos-ak-ash3/534627_477964682254266_1412043521_s.jpg" alt="">
</div>
Is this possible? I would image you copy the source URL, modify the end from s.jpg to o.jpg and the replace the old URL w/ the new one.
EDIT:
Thanks everyone for your replies & solutions, below is another solution I found...
$('.div1>img').attr('src',function(i,e){
return e.replace("s.jpg","o.jpg");
})
ex - http://jsfiddle.net/designaroni/4Da2a/
function imgSrcOverwrite() {
var imgs = document.getElementsByTagName('img'),
loopImg, fbImgs = [];
// Loop through each IMG, check if it's a facebook image &
// then replace _s.jpg with _o.jpg in the src attribute
for ( var x=0; x<imgs.length; x++ ) {
loopImg = imgs[x];
if ( loopImg.src.indexOf('photos-g.ak.fbcdn.net') > -1 ) {
loopImg.src = loopImg.src.replace('_s.jpg', '_o.jpg');
fbImgs.push(loopImg);
}
}
imgs = loopImg = null;
// return array of fb images so you can do more stuff with them
return fbImgs;
}
imgSrcOverwrite();
If you're using jQuery I'd replace the second line with
var imgs = $('.post_picture img'),
http://jsfiddle.net/CoryDanielson/jmzk2/
Here's a quick example of how it may be possible.
// get image dom element
var img = document.getElementById('imageId');
// update src
img.src = img.src.replace(/s.jpg/, 'o.jpg');
If you are using jquery,
Try to access the img tag by this -
var src = '';
$('.post_picture').find('img').each(function(){
src = $(this).attr('src').toString().replace('_s.jpg', '_o.jpg');
$(this).attr('src',src);
});

Javascript gallery with prev/next function AND thumbnail... nothing else

Short of going for something like Galleriffic
and modifying, hiding and removing elements, what would be a way to add a function by which thumbnails can also be clicked to display the image?
Much obliged to anyone who can point me in the right direction. I'm using the following by Paul McFedries at mcfedries.com.
<script type="text/javascript">
<!--
// Use the following variable to specify
// the number of images
var NumberOfImages = 3
var img = new Array(NumberOfImages)
// Use the following variables to specify the image names:
img[0] = "yellow1.jpg"
img[1] = "blue2.jpg"
img[2] = "green3.jpg"
var imgNumber = 0
function NextImage()
{
imgNumber++
if (imgNumber == NumberOfImages)
imgNumber = 0
document.images["VCRImage"].src = img[imgNumber]
}
function PreviousImage()
{
imgNumber--
if (imgNumber < 0)
imgNumber = NumberOfImages - 1
document.images["VCRImage"].src = img[imgNumber]
}
</script>
in the html:
<div class="galleryarrows">
<A HREF="javascript:PreviousImage()">
<IMG SRC="previous.png" BORDER=0></A>
<A HREF="javascript:NextImage()">
<IMG SRC="next.png" BORDER=0></A>
</div>
A quick, basic solution: Save the full size versions of your images in a folder called say, 'full_images', with the same names as the thumbnails.
Add an onClick event into the element img elements that display your thumbnails in the html, so they look something like this.
<img src = "yellow1.jpg" name = "thumb[0]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(0);" alt = "yellow"/>
<img src = "blue2.jpg" name = "thumb[1]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(1);" alt = "blue"/>
<img src = "green3.jpg" name = "thumb[2]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(2);" alt = "green"/>
In your javascript, add this function
function DisplayImage(id){
imgNumber = id;
document.images["VCRImage"].src = "full_images/" + img[id];
}
This will display in an element with the name 'VCRImage'.
Not my favourite solution this, but quick, and should work. If Javascript is new to you, then you might as well check out jQuery. It's a lot easier to use, and is way more cross-browser compatible.

Categories

Resources