Can you generate html locally, without using a server? - javascript

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>

Related

Generate array of image in javascript inside <div>

I need to make the background image in div tag and it has to change automatically, I already put the array of images inside the javascript, but the images is not showing when i'm run the site.The background should behind the menu header.
This is the div
<div style="min-height:1000px;position:relative;" id="home">
below of the div is containing the logo, menu and nav part.
<div class="container">
<div class="fixed-header">
<!--logo-->
<div class="logo" >
<a href="index.html">
<img src="images/logo.png" alt="logo mazmida" height="142" width="242">
</a>
</div>
<!--//logo-->
This is the javascript
<script>
var imgArray = [
'images/1.jpg',
'images/2.jpg',
'images/3.jpg'],
curIndex = 0;
imgDuration = 2000;
function slideShow() {
document.getElementID('home').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
You have a few issues with your script. I've made a live JSbin example here:
https://jsbin.com/welifusomi/edit?html,output
<script>
var imgArray = [
'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/220px-Homer_Simpson_2006.png',
'https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge_Simpson.png/220px-Marge_Simpson.png',
'https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png'
];
var curIndex = 0;
var imgDuration = 1000;
var el = document.getElementById('home');
function slideShow() {
el.style.backgroundImage = 'url(' + imgArray[curIndex % 3] + ')';
curIndex++;
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
There are a few issues with your script:
On the element since it's a div not an img, you need to set style.backgroundImage instead of src. Look at https://developer.mozilla.org/en-US/docs/Web/CSS/background for other attributes to related to background image CSS
Also it's document.getElementById
Optimizations
And you can use mod % trick to avoid zero reset
Use setInterval instead of setTimeout
Further optimzations
Use requestAnimationFrame instead of setTimeout/setInterval
I suggest getting familiar with your browser debugging tools which would help identify many of the issues you face.
document.getElementID('home').src = imgArray[curIndex]
You are targeting a div with an ID of home, but this is not an Image element (ie ,
But since you want to alter the background colour of the DIV, then you use querySelector using javascript and store it in a variable, then you can target the background property of this div (ie Background colour).
I hope this helps.
You are trying to change the src property of a div, but divs do not have such property.
Try this:
document.getElementById('home').style.backgroundImage = "url('" + imgArray[curIndex] + "')"
This changes the style of the target div, more precisely the image to be used as background.
As you want to change the background image of the div, instead of document.getElementID('home').src = imgArray[curIndex] use
document.getElementById("#home").style.backgroundImage = "url('imageArray[curIndex]')";
in JavaScript or
$('#home').css('background-image', 'url("' + imageArray[curIndex] + '")'); in jquery.
To achieve expected result, use below option of using setInterval
Please correct below syntax errors
document.getElementID to document.getElementById
.src attribute is not available on div tags
Create img element and add src to it
Finally use setInterval instead of setTimeout outside slideShow function
var imgArray = [
'http://www.w3schools.com/w3css/img_avatar3.png',
'https://tse2.mm.bing.net/th?id=OIP.ySEgAgJIlDQsIQTu_MeoLwHaHa&pid=15.1&P=0&w=300&h=300',
'https://tse4.mm.bing.net/th?id=OIP.wBAPnR04OfXaHuFI9Ny2bgHaE8&pid=15.1&P=0&w=243&h=163'],
curIndex = 0;
imgDuration = 2000;
var home = document.getElementById('home')
var image = document.createElement('img')
function slideShow() {
if(curIndex != imgArray.length-1) {
image.src = imgArray[curIndex];
home.appendChild(image)
curIndex++;
}else{
curIndex = 0;
}
}
setInterval(slideShow,2000)
<div style="position:relative;" id="home"></div>
code sample - https://codepen.io/nagasai/pen/JLKvME

Generate html using 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>

Use javascript selectors without jQuery to select images

I have some images like this:
<img src="http://127.0.0.1/test/images/cat01.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat02.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat03.png" alt="00" class="cat_img">
and I want to select the image names (cat01.png, cat03.png and cat03.png) with javascript (without jQuery).
How can I do that ?
I have tried :
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
console.log('Images '+images);
Thanks for help.
Or like this (no need to use Array.prototype.slice)
var images = Array.prototype.map.call(
document.querySelectorAll(".cat_img"),
function(img) {
var src = img.src,
lastIndex = src.lastIndexOf('/');
return src.slice(lastIndex + 1);
});
You can loop over your images array using map and return the part of the src attribute that you want (everything after the last /):
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
var imageNames = images.map(function( image ) {
return image.src.substring( image.src.lastIndexOf("/") + 1 );
} );
console.log(imageNames);
jsfiddle
Here is a simple example using regex with a loop.
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
for(i = 0; i < images.length; i++) {
console.log(images[i].src.replace(/.+\//, ''));
}
jsfiddle
So to build your array of names, just replace the console.log(...) line with images[i] = images[i].src.replace(/.+\//, '')

Getting images to change in a for loop in javascript

So far I created an array with 11 images, initialized the counter, created a function, created a for loop but here is where I get lost. I looked at examples and tutorial on the internet and I can see the code is seeming simple but I'm not getting something basic here. I don't actually understand how to call the index for the images. Any suggestions. Here is the code.
<script type="text/javascript">
var hammer=new Array("jackhammer0.gif",
"jackhammer1.gif",
"jackhammer2.gif",
"jackhammer3.gif",
"jackhammer4.gif",
"jackhammer5.gif",
"jackhammer6.gif",
"jackhammer7.gif",
"jackhammer8.gif",
"jackhammer9.gif",
"jackhammer10.gif")
var curHammer=0;
var numImg = 11;
function getHammer() {
for (i = 0; i < hammer.length; i++)
{
if (curHammer < hammer.length - 1) {
curHammer = curHammer +1;
hammer[i] = new Image();
hammer[i].src="poses/jackhammer" +(i+1) + ".gif";
var nextHammer = curHammer + 1;
nextHammer=0;
{
}
}
}
}
setTimeout("getHammer()", 5000);
</script>
</head>
<body onload = "getHammer()";>
<img id="jack" name="jack" src = "poses/jackhammer0.gif" width= "100" height ="113" alt = "Man and Jackhammer" /><br/>
<button id="jack" name="jack" onclick="getHammer()">Press button</button>
Following on what Paul, said, here's an example of what should work:
var hammer=["jackhammer0.gif","jackhammer1.gif","jackhammer2.gif","jackhammer3.gif",
"jackhammer4.gif","jackhammer5.gif","jackhammer6.gif","jackhammer7.gif",
"jackhammer8.gif","jackhammer9.gif","jackhammer10.gif"];
var curHammer=0;
function getHammer() {
if (curHammer < hammer.length) {
document.getElementById("jack").src= "poses/" + hammer[curHammer];
curHammer = curHammer + 1;
}
}
setTimeout("getHammer()", 5000);
The big missing element is that you need to call getElementById("jack") to get a reference to the DOM Image so that you can change it's source. If you're using jQuery or most other JS frameworks, just type $("#jack") to accomplish the same.
I don't understand the need for the for loop at all, just increment the index value [curHammer] each time you click, and reset if it passes your max index length (in this case 11).
Pseudo-Code:
currentHammer = -1
hammers = [ "a1.jpg", "a2.jpg", "a3.jpg"]
getHammer()
{
currentHammer = currentHammer + 1;
if(currentHammer > 2)
currentHammer = 0;
image.src = hammers[currentHammer];
}
a) are you just trying to show an animated gif? If so, why not use Adobe's Fireworks and merge all those gifs into a single gif?
b) you know that the way you have it the display is going to go crazy overwriting the gif in a circle right?
c) you might want to put a delay (or not). If so, make the load new gif a separate function and set a timeout to it (or an interval).
Also, you are being redundant. How about just changing the src for the image being displayed?:
var jackHammer = new Array();
for (var i=0;i<11;i++) { //pre-loading the images
jackHammer[i] = new image();
jackHammer[i].src = '/poses/jackHammer'+i.toString()+'.gif';
} //remember that "poses" without the "/" will only work if that folder is under the current called page.
for (var i=0;i<11;i++) { //updating the image on
document.getElementById('jhPoses').src = jackHammer[i].src;
}
on the document itself,
< img id='jhPoses' src='1-pixel-transparent.gif' width='x' height='y' alt='poses' border='0' />

How to populate alt fields with the src of an image for all images on page

I am working on a site that has a page that will have a couple hundred thumbnails. I would like to have the filenames (the src) of the images populate the alt fields. So for example, I currently have the thumbnails as follows:
<img src="images/thumb1.jpg" />
I would like to populate the alt fields with the filename. So, the desired result would be:
<img src="images/thumb1.jpg" alt="thumb1" />
Is there a way I can automatically generate these alt tags using the images src?
Any suggestions are appreciated. Thank you for the help!
An untested, first guess, would be:
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
images[i].alt = images[i].src;
}
JS Fiddle demo.
Just to demonstrate how much easier this can be, with a JavaScript library, I thought I'd also offer the jQuery demo too:
$('img').each(
function(){
this.alt = this.src;
this.title = this.src;
});
jQuery-based JS Fiddle demo.
Edited because I'm an idiot...
I forgot to point out that you'll need to wait for the window to finish loading (or, at least, for the document.ready event), so try it this way:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i = 0; i < numImages; i++) {
images[i].alt = images[i].src;
images[i].title = images[i].src;
}
}
And change the opening body tag to:
<body onload="makeAlt">
JS Fiddle demo.
Edited to address the OP's final question:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
var newAlt, stopAt;
for (i = 0; i < numImages; i++) {
newAlt = images[i].src.split('/').pop();
stopAt = newAlt.indexOf('.');
newAlt = newAlt.substring(0,stopAt);
images[i].alt = newAlt;
images[i].title = newAlt;
}
}
JS Fiddle, though I suspect there's a far more concise way...
To get the file name you could add to David Thomas's code...
var name = images[i].getAttribute('alt').split('/');
name = name[name.length-1].split('.')[0];
So that you end up with...
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
var name = images[i].getAttribute('src').split('/');
name = name[name.length-1].split('.')[0];
images[i].setAttribute('alt') = name;
}
(Also amazingly untested)
Here it is, with some simple DOM operations and a dash of regex magic:
var imgs = document.getElementsByTagName('img');
// This will extract the file name (minus extension) from the image's `src`
// attribute. For example: "images/thumb1.jpg" => "thumb1"
var name_regexp = /([^/]+)\.[\w]{2,4}$/i;
var matches;
for ( i = 0; i < imgs.length; i++ ) {
matches = imgs[i].src.match(name_regexp);
if ( matches.length > 1 ) {
imgs[i].alt = matches[1];
imgs[i].title = matches[1];
}
}
See JSFiddle for a demo.
var images = document.getElementsByTagName("img");
var count = images.length;
for (i=0; i<count; i++){
var src = images[i].getAttribute("src");
var path = src.split("/");
var fullname = path[path.length - 1];
var name = fullname.split(".");
var result = name[0];
images[i].setAttribute("alt") = result;
}
I think the real questions you should be asking is will all this actually help my SEO, because I assume that is the reason why you would like your alt tags populated?
There is some evidence that Google is getting better at reading Javascript, but will it run the scrip before it crawls the pages and add the alt text then index the page with that alt text and consider that alt text to provide additional value outside of the keywords it already found in your file names, especially considering that it rendered the script so it will probably know that the alt is just being copied form the file name. Or will Google simply index all the html and not even bother trying to run the javascript?
I would be interested to hear any additional insight others may have on this.
I personally feel there is a low probably that this will end up helping your SEO. If you are using a content management system you should probably be looking at how to add alt text via PHP by taking the variable for the page heading or title and inserting that to the alt text.
Unless you don't care about your SEO and are really doing this for text readers, then forget everything i just said.

Categories

Resources