I test the code in IE7, FF, Chrome, Safari and this problem occurs in Firefox only.
I have checked that the problem only occurs in FF 3.5.x, but not FF 3.0.x.
I want to make an image animation which has 10 images in total.
Currently, I use the following code to do it:
for (var i=1;i<=10;i++){
img[i] = new Image();
img[i].src = "images/survey/share_f"+i+".jpg"
}
var cornerno = 0;
function imganimate(){
$("#surveyicon").attr("src",img[cornerno].src);
//some logic to change the cornerno
setTimeout("imganimate()",1000);
}
And then change an element's src to loop through the array "img".
however, firefox keeps requesting the images continuous (I expect it only requests each unique image just once).
What should I do?
img is undefined. just add a line "var img = new Array();" before "for (var i=1;i<=10;i++){"
var img = new Array();
for (var i=1;i<=10;i++){
img[i] = new Image();
img[i].src = "images/survey/share_f"+i+".jpg";
}
var cornerno = 0;
function imganimate(){
cornerno %= 10;
cornerno++;
$("#surveyicon").attr("src",img[cornerno].src);
setTimeout("imganimate()",1000);
}
imganimate();
Try composing the images into a single image file like a sprite map and then use CSS positioning to shift the image around as a background image. It will be much faster and avoid any reloads.
You've already created ten DOM nodes, set their src and loaded the images. Why would you set the src again? You want to rotate those ten nodes in and out now. You can either toggle style.display or remove and insert the nodes.
Here's my suggestion. I'm not well versed in JQuery so there may be a few additional shortcuts I've overlooked:
var imgAmt = 10;
img = [];
for (var i=1;i<=imgAmt;i++){
img[i] = document.createElement("img");
img[i].src = "images/survey/share_f"+i+".jpg"
img[i].style.display = "none";
$("#surveyicon").appendChild(img[i]);
}
imganimate();
var cornerno = 0;
function imganimate(){
cornerno++;
cornerno = cornerno > imgAmt ? 1 : cornerno;
for (var i=1;i<=imgAmt;i++){
// hide all images but the index that matches cornerno:
img[i].style.display = i==cornerno ? "" : "none";
}
setTimeout(imganimate,1000);
}
This seems a bug in FF3.5.x.
Not sure whether the bug has already been fixed.
Related
I want to get the SRC from every <IMG> in twitter.
let n = document.getElementsByTagName("img");
for(tip of n){
console.log(tip.src);
}
and it works for other pages, but it doesn't for twitter. Finally I did this;
let n = document.getElementsByTagName("img");
function example(){
for(tip of n){
if(tip.src == "https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg"){
tip.src = "https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg";
}
}
}
setInterval(example, 100);
With setInterval it works, also, twitter loads stuff dynamically so with setInterval I can get all those new results. (How I could do that without using setInterval?)
Also, for some weird reason, the picture doesn't change. It doesn't update.
Update:
function example(){
let n = document.getElementsByTagName("div");
for(tip of n){
console.log(tip.style['background-image']);
if(tip.style['background-image'] == 'url("https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg")'){
tip.style['background-image']= 'url("https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg")';
}
}
}
setInterval(example, 10000);
Now it works perfectly, but how could I get the new data without using setInterval eeeeeeevery time and only call to the function when it's necessary?
You have to load image every time you want to iterate them, to get "fresh" img elements
Try this
function example(){
let n = document.getElementsByTagName("img"); // Moved here
for(tip of n){
if(tip.src == "https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg"){
tip.src = "https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg";
}
}
}
setInterval(example, 100);
It is not always that the images are shown with img tag.
If you see some cases on twitter, img tag's sibling is an element with img src in its styles. That element is showing the image. Obviously, this is not the case with every single image on twitter.
But for such a case, you change it's background by
let n = document.getElementsByTagName("img");
for(tip of n){
r.previousSibling.style.backgroundImage='YourImage.png'
}
Also, you have to use some kind of interval to get results that are loaded later. Or you could detect DOM changes using Mutation Observer and only fire your function on DOM change.
I'm actually trying to find a way in a js script to downloading the three first images from a specifiq URL.
I have find this way to download img file as a new filename, but this script don't limit the imgs downloads to three:
download-data-url-file.
Why only the three images from an URL ?
Because i would like to setup later a sort of timer to repeat the downloading task.
The URL is a content feed (http://feed.500px.com/500px-best)
Basically, the img source URL is avalaible if we enter in the Inspector tool on Firefox, we can see the URL source for a give image like:
<img xmlns="http://www.w3.org/1999/xhtml" src="https://drscdn.500px.org/photo/266885357/m%3D900/v2?webp=true&sig=b5a6df5651c4248defdeee0f5b4d1ec599d87d5fa69e7673b5d64cef5a4deeb7" />
So the js script will take the first image from the website, and download the .png image as a newfilename.png (just an filename exemple), reapeat the step for a second and a third image, and stop to run.
There is an short js that i have modded for my task, i assume that i can improve it by adding an var totalImages = 3 to limiting the total img downloads..
var data = canvas.toDataURL("http://feed.500px.com/500px-best/jpeg");
var img = document.createElement('img');
img.src = data;
var a = document.createElement('a');
a.setAttribute("download", "Image1.jpeg");
a.setAttribute("href", data);
a.appendChild(img);
Thank in advance.
// This code is very specific to 500PX
// I had to use itemcontent selector, as the feed was giving small icons
// as first three images.
var parents = document.getElementsByClassName("itemcontent");
var totalImages = 3;
var done = false;
var result = [];
for(var i = 0; i < parents.length && !done; i++) {
var images = parents[0].getElementsByTagName("img");
for(var j = 0; j < images.length && !done; j++) {
result.push(images[j].src);
if(result.length == totalImages)
done = true;
}
}
// The result array contains the first three images of the page.
I am calling this function on add button from my PHTML. On click of add button I want to show image of selected fruit in <div>.
function moveoutid()
{
var sda = document.getElementById('availableFruits');
var len = sda.length;
var sda1 = document.getElementById('orderFruits');
for(var j=0; j<len; j++)
{
if(sda[j].selected)
{
alert(baseUrl+"/img/"+sda.options[j].value+".jpg");
var img1=document.createElement('img').src=baseUrl+"/img/"+sda.options[j].value+".jpg";
var di=document.getElementById('d');
di.appendChild(img1);
var tmp = sda.options[j].text;
var tmp1 = sda.options[j].value;
sda.remove(j);
j--;
var y=document.createElement('option');
y.text=tmp1;
try
{
sda1.add(y,null);
}
catch(ex)
{
sda1.add(y);
}
}
}
}
In this code I have created <img> tag and passing image path to src, to show selected image on web page. It is correctly taking path of images but it is not appending <img> tag and not displaying image on web page.
Your problem is, most likely, in this line:
var img1=document.createElement('img').src=baseUrl+"/img/"+sda.options[j].value+".jpg";
This creates an element, assigns the src property to it and then assigns the value of this src property to variable img1. Instead, you should do this in two lines:
var img1 = document.createElement('img');
img1.src = baseUrl+"/img/"+sda.options[j].value+".jpg";
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' />
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.