Gallery of Images not displaying properly with document.getElementbyId() - javascript

So I'm working on a website for my job's store, a sort of gallery of our products. I've gotten the main web page, cut out the fat, put in the meat, and have tested it numerous times along the way. Now I am having some troubles with the JQuery not working properly. I have provided direct links to the JQuery code, a copy of the website itself, and the source code below..
The general layout of the JQuery(or Javascript, I'm not exactly sure which) is:
window.onload = function() {
function displayImage() {
var mainImg = document.getElementById('Main_IMG');
var caption = document.getElementById('caption');
mainImg.src = this.src;
caption.innerHTML = this.alt;
}
document.getElementById('Zero').onclick = displayImage;
document.getElementById('One').onclick = displayImage;
document.getElementById('Two').onclick = displayImage;
// Etc etc
}
Here is a segment of the website (with some extra fluff removed):
<h1 class="Wrapper Main ClearFix">Image Gallery</h1>
<div id="Main" class="Wrapper Main ClearFix">
<div id="container11">
<img id="Main_IMG" src="img/100___06/IMG_0001.JPG" alt=""><br>
<p id="caption"></p>
</div>
<div id="gallary">
<img id="One" src="img/100___06/IMG_0020.JPG" alt="Headboard Pricing">
<img id="Two" src="http://images.craigslist.org/00P0P_84oo9H7byag_600x450.jpg" alt="Needle Point Upholstered Chair Price: $40">
<!-- etc etc -->
The program is simple: When a user clicks on an image (say in a table for example), that image will display to the left of the gallery with the alt tag being the product and price and such.
The problem: At image number 16 I needed to give it a... different-from-normal tag
(tag I wanted to use: sixteen.
Tag I used: F_sixteen)
The program then worked fine for a few more 'numbers' up until the 36's and 40 where the program refuses to respond properly.
This is a link to the website as of writing this question:Here
This is a link to the actual jquery code: Here
And for those on mobile, the link to the source code is: Here
I apologize for the size of this question, as well as if this seems complicated. Thank you for viewing this, as I appreciate any help.
EDIT: I am not sure if the web page will work in Safari. If it doesn't, I'll see what I can do to change it.

OK, I hate to suggest using jQuery to someone who bravely is not. But use it. You can cut out the 40 calls to document.getElementById and reduce the risk of typos. Just include jquery in your page:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Then you can use the following code:
window.onload = function() {
function displayImage(img) {
var mainImg = document.getElementById('Main_IMG');
var caption = document.getElementById('caption');
mainImg.src = img.src;
caption.innerHTML = img.alt;
}
$("#gallary img").click(function(){
displayImage(this);
});
}
I've kept the required changes in the above code to a minimum. To 'jquerify' it further you could write this equivalent code instead:
$(function(){
var mainImg = $('#Main_IMG');
var caption = $('#caption');
$("#gallary img").click(function(){
mainImg.attr('src', this.src);
caption.html(this.alt);
});
});

Loading the site produces javascript error: "Uncaught TypeError: Object # has no method 'getElementByID'"
Examining the javascript, some of your calls are to getElementById, and some to getElementByID. Javascript is case-sensitive, you have a typo.

Related

Create an img element into <a> tag using javascript

I want to embed an image inside an tag after the image on tag loaded.
So the sequence goes like this...
<a id="anchorID">
<img onload="MyFunc(anchorID)>IMAGE1</img>
//..After image 1 loaded add
<img>IMAGE2</img>
</a>
<script>
function MyFunc(anchorID)
{
var anchorElement = document.getElementById(anchorID);
//I want to create an image tag inside the anchorElement
}
</script>
Thanks for the help.. T_T
Here's a solution, just add onload="addNextImage('#id_in_which_to_add_new_image', 'second_image_url')" to the image you want to load first. In the next example, ignore the width and style (I put them there to be able to test the functionality, making the image smaller so I don't need to scroll to see the behavior - I chose a huge image to make sure everything works as it should, and the border makes it appear sort of like a progress bar =)
<script>
function addNextImage(selector, url) {
var where = document.querySelector(selector);
if (where) {
var newImage = document.createElement('img');
newImage.src = url;
where.appendChild(newImage);
}
}
</script>
<a id="anchorID">
<img onload="addNextImage('#anchorID', 'http://animalia-life.com/data_images/wallpaper/tiger-wallpaper/tiger-wallpaper-01.jpg')" src="http://hubblesource.stsci.edu/events/iyafinale/support/documents/gal_cen-composite-9725x4862.png" width="400px" style="border: 1px solid black" />
</a>
This should work on most browsers today: IE8+ (as long as you use basic CSS2.1 selectors as the first argument), and pretty much everything else in use. (IE8+ because it depends on querySelector)
I think what you are looking for is
Javascript appendChild()
var node = document.createElement("img");//Create a <img> node
node.src="SomeImageURL";
firstImage.appendChild(node);
JQuery append()
$("#firstImageID").append("<img src="SomeImageURL"/>");
see links for more info
Javascript
jQuery
You can use the following to add an image to the anchor tag
function MyFunc(anchorID) {
var anchorElement = document.getElementById(anchorID);
if (anchorElement) {
//I want to create an image tag inside the anchorElement
var img = document.createElement("img");
img.setAttribute("src", "yourImagePath");
anchorElement.appendChild(img);
}
}
Hope that helps.

Panel only showing on specific page

I need a working javascript code which shows a certain panel only on one specific page on my website and hides it on the rest. It's a forum-esque setup.
Here's what I got so far.
<script type="text/javascript">
function ShowPanel()
{
if(document.location.href == "http://www.exampleurl.com")
{document.getElementById("panel").style.display = "block";}
else
{document.getElementById("panel").style.display = "none";}
}
</script>
<div id="panel" onload="ShowPanel">
Example text.
</div>
According to the example code I've looked up, all of this seems to be reasonable, but obviously there's an error somewhere. Nothing happens.
Thanks for checking!
The problem is that the onload event cannot be used on a DIV element. onload can only be used on the document body or an external resource (iframe, image, scripts).
Your best bet is to place your JavaScript at the bottom of the page instead.
e.g.
<div id="panel">
Example text.
</div>
<script language="JavaScript">
if(document.location.href == "http://www.exampleurl.com"){
document.getElementById("panel").style.display = "block";
}
else {
document.getElementById("panel").style.display = "none";
}
</script>
Check what the document.location.href really is on the page by typing it into your console (F12, usually). For instance, most browsers will add the trailing slash onto a server name even if there isn't one in the URL. The match has to be exact for your code to work as written.
Another options is to compare document.location.pathname, which will have everything after the server name. If you want to make a case insensitive compare, you can use document.location.pathname.toLowerCase().

How can I remove default image icon

Images in which I have facing the cross sign problem which is appear in chrome and IE
the scenario which i want from external java script file(i want something like this).
first image having a cross icon when image tag not find the image from the source. mozilla will handle this very smartly but chrome and IE show a cross icon which i don't want..
i find out the solution which is not generic i have to pass a transparent image url when image not getting the image from specified url on every image tag..
something like this
<img src="i/ibm.png" onerror="this.src='i/1x1trns.png';">
but in my page there are more than 20 image and in a whole project more than 200 so in that case i want to handle this from a single external javascript file ...
so any one how know about this problem please tell me a solution...Thnx for co-operation
It's a bit dirty to have jQuery defined in the <head /> tag but you'd need to do this for $.ready, if you can write your own $.ready then it'd be just a bit of code in our <head />.
OR
You'd need to add jQuery before you have those images.
Try this code
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("img").on("error", function() {
$(this).attr("src", "i/1x1trns.png");
});
});
</script>
<img src="not-a-valid-image.png" alt="Logo not found" />
</body>
I have used this way in one of my projects.
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
(function(img_elem) {
var img = new Image();
img.src = img_elem.src;
img.onerror = function() {
img_elem.src = 'i/1x1trns.png';
};
})(imgs[i]);
}
http://jsfiddle.net/Ypa7N/

jQuery, JavaScript, HTML: how to load images after everything else is loaded?

I have a very complex page with a lot of scripts and a rather long loading time. On top of that page I want to implement the jquery Nivo Slider (http://nivo.dev7studios.com/).
In the documentation it says I have to list all images for the slider inside of a div#slider
<div id="slider">
<img src="images/slide1.jpg" alt="" />
<img src="images/slide2.jpg" alt="" title="#htmlcaption" />
<img src="images/slide3.jpg" alt="" title="This is an example of a caption" />
<img src="images/slide4.jpg" alt="" />
</div>
However I might have 10 images with a 1000x400px which is quite big. Those images would load when the page loads. Since they are in my header this might take quite a while.
I looking for a way to use any jquery Slider Plugin (like the nivo slider) but either dynamically load images or load all those images after everything else on my page has loaded.
Any idea how I could solve that?
Is there even a way to start a javascript process after everything else on the page has loaded? If there is a way I might have an solution for my problem (using the jquery ajax load() method) ... However I have no idea how to wait for everything else to load and then start the slider with all the images.
Here's what we did and its working great. We skipped setting src attribute of img and added img-location to a fake attribute lsrc. Then we load a dynamic image with lsrc value, and set the src of actual image only after its loaded.
Its not about faster loading, but its about showing the images only when its downloaded completely on your page, so that user do not have to see that annoying half-loaded images. A placeholder-image can be used while the actual images are being loaded.
Here's the code.
$(function(){
$.each(document.images, function(){
var this_image = this;
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
//this_image.src = options.loading; // show loading
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
var img = new Image();
img.src = lsrc;
$(img).load(function() {
this_image.src = this.src;
});
}
}
});
});
Edit: Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.
In addition to Xhalent's answer, use the .append() function in jQuery to add them to the DOM:
Your HTML would just have:
<div id="slider">
</div>
And then your jquery would be:
jQuery(function(){
$("#slider").append('<img src="images/slide1.jpg" alt="" />');
});
check out jquery load() event, it waits for everything including graphics
$(window).load(function () {
// run code
});
on load you could then load the images using:
var image = new Image();
image.src = "/path/to/huge/file.jpg";
You can add a function onload to the image too
image.onload = function() {
...
}
I am using the below to power my slider and improve the page load performance.
for (var i = document.images.length - 1; i >= 0; i--) {
var this_image = document.images[i];
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
$(this_image).attr("src",lsrc);
}
}
}
the best way to use is b -lazy js.
bLazy is a lightweight lazy loading image script (less than 1.2KB minified and gzipped). It lets you lazy load and multi-serve your images so you can save bandwidth and server requests. The user will have faster load times and save data loaded if he/she doesn't browse the whole page.
For a full list of options, functions and examples go to the blog post: http://dinbror.dk/blog/blazy.
The following example is a lazy loading multi-serving responsive images example with a image callback :) If your device width is smaller than 420 px it'll serve a lighter and smaller version of the image. When an image has loaded it removes the loader in the callback.
In Html
<img class="b-lazy"
src="placeholder-image.jpg"
data-src="image.jpg"
data-src-small="small-image.jpg"
alt="Image description" />
In js
var bLazy = new Blazy({
breakpoints: [{
width: 420 // Max-width
, src: 'data-src-small'
}]
, success: function(element){
setTimeout(function(){
// We want to remove the loader gif now.
// First we find the parent container
// then we remove the "loading" class which holds the loader image
var parent = element.parentNode;
parent.className = parent.className.replace(/\bloading\b/,'');
}, 200);
}
});
Example
jquery has a syntax for executing javascript after document has loaded:
<script type="text/javascript">
jQuery(function(){
//your function implementation here...
});
</script>

Refreshing images on a page periodically

I'm building a page to display a bunch of webcam images and update them periodically so that the page can be used for at-a-glance monitoring. However, I'm having issues getting the periodic reload working. My code looks something like:
<div class='cameras'>
<div class='camera'>
<h4>Desk</h4>
<img height='240' src='http://somehost/cameras/cam0/lastsnap.jpg' width='320'>
</div>
<div class='camera'>
<h4>Main Room</h4>
<img height='240' src='http://somehost/cameras/cam1/lastsnap.jpg' width='320'>
</div>
<div class='camera'>
<h4>Studio</h4>
<img height='240' src='http://somehost/cameras/cam2/lastsnap.jpg' width='320'>
</div>
</div>
Ideally I'd like to get these things reloading every couple of seconds from their specified URLs without having to generate individual JS for each camera. I've got jQuery in use for a few other bits and pieces, so sticking to that would be great - then again, a plain JS solution is fine too.
Any ideas, StackOverflow JS Gods?
Okay, solved this:
function refreshCameras() {
$('.camera img').attr('src', function(i, old) { return old.replace(/\?.+/,"?i=" + (Math.random()*1000)); });
setTimeout(refreshCameras, 1000);
}
function refreshCamerasFirst() {
$('.camera img').attr('src', function(i, old) { return old + "?i=" + (Math.random()*1000); });
setTimeout(refreshCameras, 1000);
}
$(function() {
setTimeout(refreshCamerasFirst, 1000);
});
Will take all img elements in a "camera" class, and refresh them every second with cache-busting via a random number added to the URL, which is changed every reload without making the URL obscenely long using a regexp to replace the existing number.
Generate image sources to the images [for regular intervals of time]
var img = []; //just an image source. you can write your own code for image source
img[0] ='http://site.com/pics/pic.jpg';
img[1] ='http://site.com/pics/pic1.jpg';
img[2] ='http://site.com/pics/pic2.jpg';
img[3] ='http://site.com/pics/pic3.jpg';
$(function() {
$.each(img, function(i, val) {
var images = new Image();
images.src = val; //preloading images for my example purpose
});
function reload() {
$('img.alter').each(function() { //generate a url for image source.
var src = img[Math.floor(Math.random() * img.length)];
$(this).attr('src',src);
});
}
setInterval(reload , 5000)
});
Test it here
PS :this technique doesn't require the reloading of entire page
Try rewriting meta tag on you page as
<meta http-equiv="Refresh" content="2; URL=yourpage.php">
It works cool with the text.Checkout with images
If you want to refresh the page in a specified duration you can do that in html also
Add this tag to your page head tag
<meta http-equiv="refresh" content="1">
here content is the duration in seconds
Refer this
http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm

Categories

Resources