Why does one of two identical Javascripts work in Firefox? - javascript

I have two image swap functions and one works in Firefox and the other does not. The swap functions are identical and both work fine in IE. Firefox does not even recognize the images as hyperlinks. I am very confused and I hope some one can shed some light on this for me. Thank you very much in advance for any and all help.
FYI: the working script swaps by onClick via DIV elements and the non-working script swaps onMouseOver/Out via "a" elements. Remember both of these work just fine in IE.
Joshua
Working Javascript in FF:
<script type="text/javascript">
var aryImages = new Array();
aryImages[1] = "/tires/images/mich_prim_mxv4_profile.jpg";
aryImages[2] = "/tires/images/mich_prim_mxv4_tread.jpg";
aryImages[3] = "/tires/images/mich_prim_mxv4_side.jpg";
for (i=0; i < aryImages.length; i++) {
var preload = new Image();
preload.src = aryImages[i];
}
function swap(imgIndex, imgTarget) {
document[imgTarget].src = aryImages[imgIndex];
}
<div id="image-container">
<div style="text-align: right">Click small images below to view larger.</div>
<div class="thumb-box" onclick="swap(1, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_profile_thumb.jpg" width="75" height="75" /></div>
<div class="thumb-box" onclick="swap(2, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_tread_thumb.jpg" width="75" height="75" /></div>
<div class="thumb-box" onclick="swap(3, 'imgColor')"><img src="/tires/images/thumbs/mich_prim_mxv4_side_thumb.jpg" width="75" height="75" /></div>
<div><img alt="" name="imgColor" src="/tires/images/mich_prim_mxv4_profile.jpg" /></div>
Not Working in FF:
<script type="text/javascript">
var aryImages = new Array();
aryImages[1] = "/images/home-on.jpg";
aryImages[2] = "/images/home-off.jpg";
aryImages[3] = "/images/services-on.jpg";
aryImages[4] = "/images/services-off.jpg";
aryImages[5] = "/images/contact_us-on.jpg";
aryImages[6] = "/images/contact_us-off.jpg";
aryImages[7] = "/images/about_us-on.jpg";
aryImages[8] = "/images/about_us-off.jpg";
aryImages[9] = "/images/career-on.jpg";
aryImages[10] = "/images/career-off.jpg";
for (i=0; i < aryImages.length; i++) {
var preload = new Image();
preload.src = aryImages[i];
}
function swap(imgIndex, imgTarget) {
document[imgTarget].src = aryImages[imgIndex];
}
<td>
<img name="home" src="/images/home-off.jpg" alt="Home Button" border="0px" />
</td>

Both your examples work for me, though they're pretty unappealing examples of ancient Netscape 3-era coding.
var aryImages = new Array();
aryImages[1] = "/tires/images/mich_prim_mxv4_profile.jpg";
Arrays are 0-indexed. Currently your loop will try to access aryImages[0] and get an undefined, which is will try (and fail) to preload. There is very rarely any use for the new Array constructor today. Instead use array literals:
var images= [
'/tires/images/mich_prim_mxv4_profile.jpg',
'/tires...
];
also:
document[imgTarget].src = aryImages[imgIndex];
We don't do that, or <img name> any more. In preference, give the image an id attribute and access it with document.getElementById().
Otherwise this causes all sorts of problems when image names clash with document properties and other named items on the page. Maybe you've got a name clash problem, something else called “home” in part of the document we can't see. Though if “does not even recognize the images as hyperlinks” means you aren't getting the pointer changing over the links or showing the link address, I suspect what you've actually got is a layout problem in code we can't see here, where you've accidentally positioned another element over the top of the nav so it can't be clicked on.
Anyway, it's poor for manageability, usability and accessibility to be loading images into an element like this. Use normal links to the images (so they work without JavaScript) and add progressive-enhancement JS on top, eg.:
<style type="text/css">
.thumb { display: block; }
.thumb img { width: 75px; height: 75px; border: none; vertical-align: top; }
</style>
<a class="thumb" href="/tires/images/mich_prim_mxv4_profile.jpg">
<img src="/tires/images/thumbs/mich_prim_mxv4_profile_thumb.jpg" alt="" />
</a>
<a class="thumb" href="/tires/images/mich_prim_mxv4_tread.jpg">
<img src="/tires/images/thumbs/mich_prim_mxv4_tread_thumb.jpg" alt="" />
</a>
<a class="thumb" href="/tires/images/mich_prim_mxv4_side.jpg">
<img src="/tires/images/thumbs/mich_prim_mxv4_side_thumb.jpg" alt="" />
</a>
<img id="thumbshow" src="/tires/images/mich_prim_mxv4_profile.jpg" alt="" />
<script type="text/javascript">
// Bind to links with thumb class
//
for (var i= document.links.length; i-->0;) {
if (document.links[i].className==='thumb') {
// Preload main image
//
var img= new Image();
img.src= document.links[i].href;
// When clicked, copy link address into image source
//
document.links[i].onclick= function() {
document.getElementById('thumbshow').src= this.href;
return false;
}
}
}
</script>
Similarly, most people do simple rollovers with CSS background images these days. If you use CSS Sprites, you don't even need two separate images, so no preloading or JavaScript of any kind is necessary.

Check Firebug for errors - the Console will tell you whether it's encountering any JS errors, and the Net panel will tell you whether any requests failed.

Why not put the events on the images instead of the links and see if that helps?
Like:
function swap(el, imgTarget) {
el.src = aryImages[imgIndex];
}
and
<img name="home" src="/images/home-off.jpg" alt="Home Button" border="0px" onMouseOver="swap(this, 'home')" onMouseOut="swap(this, 'home')" />

Just checked up on this. If you are using XHTML, it may not be the JavaScript that is corrupt, but your markup: XHTML needs tags and attributes to be specified in lowercase. I assume, that IE in its much-to-desire standards support perhaps partially ignores this, and evaluates your latter example as you think it should. But Firefox, which, you know, is much more standards compliant, may treat this as an improperly formatted attribute and ignores it.
Like:
<div onclick="swap(1, 'imgColor')"></div> <!-- Should work -->
<a onMouseOver="swap(1, 'home')"></a> <!-- May not work -->
Note, that this may not be the solution at all, just a possible issue.

Bobince made many very well thought out and proper suggestions to correct and enhance my code. For that I am very grateful. He suggested that because the links were not being recognized that I probably had an element that was covering over the menu. He was 100% correct. The header DIV below the menu had a height set to "auto" which caused it to cover from the top of the document down to the bottom of the header. This covered the menu and FF would not allow access to the links below it. I made a quick adjustment to the height and added a top margin for correct placement and now my menu is able to be accessed. I thought I was going crazy when I was not getting any JS errors in Firebug. The thought never crossed my mind to check for an overlapping element. Thanks a MILLION Bobince!!!
Thank you to all for your suggestions and help.

Related

Pulling Second Image Source Instead of First Using JQuery

I am new to jquery and I am trying to scrape the image source of the second img tag within a div, but can't seem to figure out the correct syntax to pull the second image by id. I feel like this isn't complicated to do, but after trying multiple ways of doing it I'm still stuck and keep getting an "undefined" error. Also not sure if "find" is not the best way to pull this and maybe I should be using something like "getElementbyID"?
Here is the source code I am trying to pull from:
<div class="mainImage" style="width:438px; height:333px;">
<img src="images/default/zoom.png" alt="Click here to see slideshow"
title="Click here to see slideshow" class="zoom" style="display: none;">
<img id="property_image"
src="http://website.com/images/assets/6695_18262.jpg" show="1"
style="width: 438px; height: 333px;">
</div>
Here is what I have:
$('.mainImage').each(function(i, element){
var imgID = $(element).find('img');
var img = $(imgID).find('#property_image').attr('src');
console.log (img);
Any help is much appreciated!
You can simply, use
var img = $('#property_image');
console.log(img.attr('src'));

JavaScript/jQuery - how to show html div content randomly on page load

This is my first ever question here so please bear with me (also new to programming) I will try my best to explain as clearly as I can. Basically I want to show the div content in random order everytime the page is loaded, this question has already been asked before and I have come across some answers to this but most of them are quite complicated for me. But I found a very simple answer ( Random Div Order on Page Load )
that I tried but I am not sure why won't it work for me, may be it's a little outdated?. I am pasting the code below to visualise for you lot, here are the divs in the html content that need to be randomised:
<div class="story-container">
<div class="story">
<img src="#" alt="some text">
<h4>Story Title</h4>
</div>
<div class="story">
<img src="#" alt="some text">
<h4>Story Title</h4>
</div>
</div>
<div class="story-container">
<div class="story">
<img src="#" alt="some text">
<h4>Story Title</h4>
</div>
<div class="story">
<img src="#" alt="some text">
<h4>Story Title</h4>
</div>
I may add more 'story-container' class divs in the future.
Below is the script that I got from the post given in the link I provided above (I replaced the target class with my own class 'story'):
<script>
var cards = $(".story");
for (var i = 0; i < cards.length; i++) {
var target1 = math.floor(math.random() * cards.lenth - 1) + 1;
var target2 = math.floor(math.random() * cards.lenth - 1) + 1;
cards.eq(target1).before(cards.eq(target2));
}
</script>
I have tried using this code javascript code within the same html page, in the header as well as at the end of body part. I also tried saving it externally and linked to it from within my html page but no luck.
My jQuery link/version is as follows:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3
/jquery.min.js"></script>
I import this jQuery code before running the js script to randomise the divs.
Not sure where things are going wrong, any help will be greatly appreciated, thank very much in advance guys!
[PROGRESS]
Thank you very much guys for your prompt replies and detailed guidance, #Hill #fermats_last_nerve #jritchey #Quiver, although you fixed the code but still it is not working in my browser which is really strange because it works perfectly in jsfiddle, codepen and plunkr. If it is working in online tools it should work in my browser as well.
I am using WAMP as a server to test my php pages on Windows 10, I normally use Firefox browser but I have test this code on Microsoft Edge as well but no joy.
Thank you again for taking time to help me with this.
I debugged your code in this codepen. Basically you had 3 errors
There are typos in your definitions for target1 and target2
cards.lenth should be cards.length
The variable cards: var cards = $(".article") is selecting all elements with the class "article", but you don't have any elements with that class, I assume you mean var cards = $(".story")
Make sure you capitalize Math when you use it.
(EDIT) Looks like someone edited your post to have the correct class in the selector so #2 no longer makes sense in light of the new edited question but I'll leave it in case you do not notice the edit for whatever reason.
I've noticed a few typos in your code. Replace your jQuery with the code below and it should work as it does in this jsfiddle.
var cards = $(".story");
for (var i = 0; i < cards.length; i++) {
var target1 = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target1).before(cards.eq(target2));
}

Loading images in javascript the interactive way without breaking compatibility

On my website, I share a lot of large images. I use the following HTML tags to display the images:
<img src="/path/to/image" width=x height=y alt="whatever">
Of course the values are replaced with proper values.
I would like to implement a solution so that all browsers (including those capable of supporting ONLY basic HTML and images including the Arachne browser) can access the image, while the browsers with javascript can see the image loading in action. (for example, the loading screen followed by the image appearing instantly)
The following URL gave me an idea:
http://blog.teamtreehouse.com/learn-asynchronous-image-loading-javascript
It suggested I should use this type of javascript
var image = document.images[0];
var downloadingImage = new Image();
downloadingImage.onload = function(){
image.src = this.src;
};
downloadingImage.src = "http://an.image/to/aynchrounously/download.jpg";
and this type of CSS:
img {
width: 600px;
height: 450px;
background: url(loading.gif) 50% no-repeat;
border: 1px solid black;
border-radius: 5px;
}
The problem with this setup is that browsers that don't support javascript or CSS will always see the loading graphic and therefore become frustrated.
Is there a way I can achieve this loading effect but still allow browsers without javascript or CSS to still see the proper image?
The only thing I can think of is to use javascript to somehow force-stop an image from loading but I don't know if such commands exist. In code, I'm thinking:
<script>
document.getElementById('delayme').dontLoadImage=true;
//stop image from loading
//ajax code to fetch image url as if it was html
document.getElementById('delayme').dontLoadImage=false;
//let image continue loading
</script>
<img ID="delayme" src="image.jpg" width=100 height=100 alt="image">
Any ideas?
and remember, the image must appear regardless of whether the user has javascript enabled or not.
UPDATE
So far, this code works for my needs, but only if both javascript and CSS are enabled or if both javascript and css are disabled. However if CSS is enabled and javascript is disabled, then the image stays hidden. How do I fix this?
<style>
img{display:none}
</style>
<div ID="loading">
</div>
<script>
document.getElementById("loading").innerHTML="Loading picture...";
</script>
<img src="http://127.0.0.1/x.jpg" onload="func()">
<script>
function func(){
document.images[0].style.display="block";
document.getElementById("loading").innerHTML="Picture loaded";
}
</script>
You can make something like this:
var asyncImgs = []; // empty array to store the img src's to load them asyncronously
var imgs = document.getElementsByTagName("img");
for(i = 0; i < imgs.length ; i++) {
asyncImgs.push(imgs[i].src); // store the src
imgs[i].src = null; // remove the src
}
With this method, the non-javascript browsers render the normal <img> tag, but with javascript you iterate all images in page, stores the src into an empty array, and then remove the src of the image. You can add your code to load images with new Image() now.
Good luck!
This will work with CSS on and JS off or both on. I don't know if I've seen anyone running JS with CSS off, but if that is something you are trying to solve, I'll have to rethink this quite a bit. I'll be honest, it's not really pretty, but it works.
If only CSS is enabled or if both JS and CSS are disabled, the page loads like any other basic HTML page. The images are loaded from the src.
Once we have JS support, we insert a loading <div> before the image and hide the image until it is loaded at which time we show it and remove the loading div. This is the best case I could think of without having to enclose every image tag in a <div> in the HTML.
HTML/JS:
<img src="https://upload.wikimedia.org/wikipedia/commons/1/13/05S_Jan_7_2012_1035Z.jpg" />
<img src="https://placehold.it/998x999.png"/>
<img src="https://placehold.it/997x999.png"/>
<img src="https://placehold.it/996x999.png"/>
<img src="https://placehold.it/995x999.png"/>
<img src="https://placehold.it/994x999.png"/>
<img src="https://placehold.it/993x999.png"/>
<img src="https://placehold.it/992x999.png"/>
<img src="https://placehold.it/991x999.png"/>
<img src="https://placehold.it/990x999.png"/>
<img src="https://placehold.it/999x991.png"/>
<img src="https://placehold.it/999x992.png"/>
<img src="https://placehold.it/999x993.png">
<img src="https://placehold.it/999x994.png"/>
<script>
var imgList = document.getElementsByTagName('img');
for (var i = 0; i < 3; i++) {
imgList[i].insertAdjacentHTML('beforebegin', '<div id="loading' + i + '" style="height:' + imgList[i].clientHeight + 'px;width:' + imgList[i].clientWidth + 'px;background: url(\'http://loading.io/assets/img/default-loader.gif\') center no-repeat;z-index:9999;"></div>');
imgList[i].style.display = "none";
imgList[i].onload = function() {
this.style.display = "block";
this.previousSibling.remove();
};
}
</script>
CSS:
img {
display: block;
width: 600px;
height: 450px;
border: 1px solid black;
border-radius: 5px;
}
Demo: https://jsfiddle.net/hopkins_matt/abychvxc/
After looking at answers and my own testing, it turns out that I needed the noscript tag and that I needed to fully generate a new image to attach to the existing DOM structure. Because of Internet Explorer's bugs, I forced internet explorer to load the image an old-fashioned-ish way where the status isn't updated as the image loads. In other browsers, the load is more progressive because those browsers were invented correctly (I hope). Nevertheless, this code works for me and I will use it as my starting point.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div ID="LOAD"></div>
<div ID="IMAGE">
<noscript>
<img src="/x.jpg">
</noscript>
</div>
<script>
var x=document.getElementById('LOAD');
x.innerHTML='Loading...';
downloadingImage=document.createElement('IMG');
if (navigator.userAgent.indexOf("MSIE") == -1){
downloadingImage.onload=function(){
x.innerHTML='';
document.getElementById('IMAGE').appendChild(downloadingImage);
}
}else{
x.innerHTML='IE';
document.getElementById('IMAGE').appendChild(downloadingImage);
}
downloadingImage.src = "/x.jpg";
</script>
</body>
</html>

Javascript for navigation working on certain submenus, but not others?

If you go to http://anderson.snappywash.com/, you will see that it's a nice looking site. The navigational submenus appear to be working, BUT if you inspect element, you will see that Under the PRICING tab, there are submenus that follow the exact calling actions as the others that do not get displayed. Specifically, under div#Price_links you will find them and you will see the others too (ie: Wash links, About Links etc.) they are using this JS:
function showDD(id) {
var element = id + "_links";
document.getElementById(element).style.display = "block";
}
function hideDD(id) {
var element = id + "_links";
document.getElementById(element).style.display = "none";
}
Why are the links under pricing not being displayed?
they follow the exact same "set-up" in terms of calling as the other submenus that are being displayed. I have been cracking my brain on this one for a little while and can't seem to figure it out. Any ideas? anyone?
I took a look at the site and this is what I saw.
Here's the HTML for the working item:
<img src="images/nav/unlimited.png" onmouseover="this.src='images/nav/unlimited_ov.png'; showDD('Wash');" onmouseout="this.src='images/nav/unlimited.png'; hideDD('Wash');" border="0">
Here's the HTML for the not working menu item:
<img src="images/nav/pricing.png" onmouseover="this.src='images/nav/pricing_ov.png';" onmouseout="this.src='images/nav/pricing.png';" border="0">
It seems like you left out the calls to showDD and hideDD in the item that isn't working.
The difference is that you are calling showDD in the onmouseover of the elements it's working on (example line 58:)
<a href="zoompass.cfm">
<img src="images/nav/unlimited.png" onmouseover="this.src='images/nav/unlimited_ov.png'; showDD('Wash');" onmouseout="this.src='images/nav/unlimited.png'; hideDD('Wash');" border="0" />
</a>
But not in the pricing image
<a href="pricing.cfm">
<img src="images/nav/pricing.png" onmouseover="this.src='images/nav/pricing_ov.png';" onmouseout="this.src='images/nav/pricing.png';" border="0" />
</a>

Using jQuery to Swap Out Body Background Image on click and randomize on load

I've got a body background image that is being "placed" by a plugin called ezBigResize that basically allows the image to scale with the browser window.
The designer wants to image though to be able to be swapped out by a series of thumbnails on the page, along with that image being randomized on page load from that series of images.
Initially before those two additions, I just had it setup like this:
$(document).ready(function() {$("body").ezBgResize({img : "/lib/img/bkgr/mainBG.jpg"});});
Then this is the code now (in a jQuery Tools scrollable)
<div id="bkgrSelector">
<div class="scrollNav">
<a class="prev browse left"></a>
</div>
<div class="scrollable">
<div class="items">
<img src="/lib/img/bkgr/selections/main-bg.jpg" width="77" height="44" />
<img src="/lib/img/bkgr/selections/main-bg02.jpg" width="77" height="44" />
<img src="/lib/img/bkgr/selections/main-bg03.jpg" width="77" height="44" />
</div>
</div>
<div class="scrollNav">
<a class="next browse right"></a>
</div>
</div>
I'm a little over my head though to allow these to both randomize on page load and to swap out the image via the value in the href.
I tried something like this, but it didn't work and is obviously inclomplete. Plus, it doesn't address the randomization at all.
$('#bkgrSelector .items img[href]').click(function()
{
$("body").css("background-image", "url()");
});
Any ideas, help, etc. would be appreciated.
Are those <img> pointing at the full-sized image file? I absolutely LOATHE sites that use full-size images and shrink them to thumbnail size. The load times are attrocious.
If they're actually thumbnail-sized images, you won't be able to use that url directly as your background url, as you'd just be stretching a small thumbnail-sized image to cover the window and get a hideous pixelized mess.
If the page is being dynamically generated, you'd want to create a JS array that contains the URLs of the full-sized image urls, so that when a thumbnail is clicked, you can get the fullsize url from that array. Or at least have a standardized naming convention so a simple string manipulation lets you turn the thumbnail url into a fullsize image url.
Once you've got that array, it's a simple matter to randomize a choice from it:
var imgs = ['/url/for/img1.jpg', '/url/for/img2.jpg', etc....];
$(document).ready(function() {
randomUrl = imgs[Math.round(Math.random() * (imgs.length - 1)) + 1];
$("body").css("background-image", 'url(' + randomURL + ')');
});

Categories