I have a JS code, that gets called in different web pages of my clients. I want to fetch the total number of images. I want only those images that are visible to the user and not just any other images. This is my JS code
function getImageCount(topWindow) {
try {
var images = topWindow.document.getElementsByTagName('img');
var imageCount;
for (var i=0, length = images.length; i < length; i++) {
var image = images[i];
var clientWidth = image.clientWidth;
if(clientWidth && clientWidth > 1) {
var src = image.getAttribute('src');
if(src) {
src = src.toLowerCase();
if(src.indexOf('.jpg') !== -1 ||
src.indexOf('.jpeg') !== -1 ||
src.indexOf('.gif') !== -1 ||
src.indexOf('png') !== -1) {
imageCount = imageCount ? ++imageCount : 1;
}
}
}
}
return imageCount;
} catch (e) {
processError("getImageCount", e);
}
}
var imageCount = getImageCount(top);
I have been trying a lot to stabilize this code so that it works correctly across all different types of web pages. Basically what I want is a generic code that captures image counts correctly.
Eg:
My code gives image count as 1 for http://www.msn.com/en-us/news/other/one-free-agent-every-nfl-team-should-sign-this-offseason/ss-AAmLlC0#image
What I want is a GENERIC CODE that gives me a correct image count irrespective of where it runs. Can some one give me some detailed solutions.
I would appreciate a lot.
To simplt count all the images (<img>) on the page:
document.images.length
And to count all the "visible" images (ones with width and height):
[...document.images].filter(img => img.clientWidth && img.clientHeight).length
This will give you the number of images on the page. This does not include CSS images. since your code didn't either then I take it you want <img> ones
I didn't quite understand the meaning of irrespective of where it runs.. can you elaborate?
// Extract images
websiteImages = document.getElementsByTagName('img');
for (url in websiteImages)
console.log(websiteImages.length);
//Extract inbound and outbound links
Links = document.querySelectorAll('a');
for (link in Links)
console.log(Links[link].href);
Paste this Scripts into your console of browser
Check on the Below Link/ any Link you like
(https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en&gl=IN&ceid=IN:en)
The above-mentioned script will give all the Images present in the webpages.
And the second script will give all the number of Inbound and Outbound/exit links
Just apply Some filter as per your use case and you will be good to go.
Use this simple approach for links
$$('a').length
To count the number of images on a webpage use the below code:
$$('img').length
Related
My function is as follows:
function mySound() {
var eventTable = document.querySelector("#eventContent");
var eventCella=eventTable.getElementsByClassName("ago_eventlist_activity");
var eventCellb = eventTable.getElementsByClassName("missionFleet");
for (var i = 0; i < eventTable.rows.length-1; i++) {
var cella = eventCella[i];
var cellb = eventCellb[i];
if (cella.src == "Activity15.gif" && cellb.src == "60a018ae3104b4c7e5af8b2bde5aee.gif")
{theSound = probeSound; oaPlaySound();}
if (cella.img == "Activity15.gif" && cellb.img == "cd360bccfc35b10966323c56ca8aac.gif")
{theSound = attackSound; oaPlaySound();}
if (cella.img == "Activity15.gif" && cellb.img == "575dfbbe877f58d6c09120ffbcaabe.gif") {theSound = attackSoundRIP; oaPlaySound();}
} /* for i */
}
*I can't use ...byid cause it doesn't seem to have one?
I am including a link to the FireFox inspect element so you can see what I can see to try to make this work.
Image of InspectElement:
Any help would be helpful I am just trying to code this for a friend and I really don't know java at all.
Thanks
There is a difference between Java and javascript. I'm guessing you mean javascript since that is what the code appears to be.
There are a few issues with the code
cella.img does not target the image inside of the cell, you'll need to target the image first, or use find the image inside the cell.
var eventCella = eventTable.querySelector(".missionFleet img");
or
var imgb = eventCellb[i].querySelector("img");
Does the ago_eventlist_activity cell even contain an image? There doesn't seem to be one in the screenshot.
Checking the image src needs to include the complete url, unless you use an indexOf...
if (imgb.src.indexOf('60a018ae3104b4c7e5af8b2bde5aee.gif') > -1) {
// do something
}
I hope that helps. Please, the next time you ask a question, include the HTML instead of a screenshot. Or better yet, include a demo (jsFiddle) that shows the problem because it makes it easier for others to help. Not everyone will take the time or make an effort.
So I have a web page that has an image slide show of 6 different images 50x50 pixels. I would like to have it so that; when a user clicks the image, a new window pops up with the same images doing the same thing, but change the size to 200x200px. Is there an easy way to do this, am I close?
HTML:
JS:
var mainImg = document.getElementById("slide");
var imgArray = ["slicedImg_01.gif", "slicedImg_02.gif", "slicedImg_03.gif", "slicedImg_04.gif", "slicedImg_05.gif", "slicedImg_06.gif"];
var index = 0;
function imgCycle(){
mainImg.setAttribute("src", imgArray[index]);
index++;
if (index >= imgArray.length){
index = 0;
}
}
setInterval (imgCycle,500);
function fullSize(){
var big = window.open('assignment 1.1.html')
document.getElementById("slide").height="200";
}
You can access child element using your window object using plain javascript
var big = window.open('assignment 1.1.html')
big.document.getElementById("slide").height="200";
check this question and its answer, may it will help you.
how-can-i-access-the-dom-tree-of-child-window
I have a page in a CMS that I can only edit parts of. I want to change the images it displays to larger ones. The system automatically created multiple sizes and stores them so all I would need to do is change it from /location/image-1.jpg to /location/image-2.jpg
I tried the following code unsuccessfully
<body onload="replaceScript();">
<script type="text/javascript">
function replaceScript() {
var toReplace = '-1.jpg';
var replaceWith ='-2.jpg';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>
Any ideas?
My guess is you've got a series of images that you want changed and its only changing one for you. A general innerHTML replace probably isn't the best way to go about changing image sources.
Try something like this:
function replaceScript() {
var images = document.querySelectorAll('img');
for(var i = 0, l = images.length; i < l; i++){
images[i].src = images[i].src.replace("-1.jpg", "-2.jpg");
}
}
I'm currently making a game in JS, and I faced a problem.
I got an 2D array that stores an image, now I want some random pic to be changed every 1 second, everything is working but, I don't know how I can change the picture.
Do I have to print all the other images if I want to change the random cell in the array?
I'm almost sure that there's another way to change it without doing it.
I'll be glad for help, if anyone needs other explanation I'll be glad to.
You can try using something like this in your header. It should call changePic() every second, incrementing through your picture array, and setting the new picture on an image element.
//know your array sizes
var max_x = picArr.length;
var max_y = picArr[0].length;
var current_x = 0;
var current_y = 0;
function changePic()
{
if(current_y == max_y-1)
{
if(current_x == max_x-1)
{
current_x = 0;
current_y = 0;
}
else
{
current_x++;
current_y = 0;
}
}
else
current_y++;
var pic = picArr[current_x][current_y];
getElementById('randomImage').setAttribute('src', pic);
window.setTimeout(changePic, 1000);
}
setTimeout(changePic, 1000);
https://developer.mozilla.org/en/DOM/window.setTimeout
I would start out with something like
var ImageOne = new Image();
ImageOne.src = "UrlToImage";
And so on just to make sure all the images are loaded when the game starts
Thereafter I would be using jQuery:
$("#IdOfImg").attr("src", ImageOne);
You might want to try using a css class for the elements with a background image rather dan adding images to the DOM. I think a css class for back.png and one for the 1.png should do the trick.
Toggle the classes on the td elements every second.
Hope this helps.
I want to display several images of the same size at the same position, one at a time, with a 5s interval between each change. To do so I've used jQuery.Timer, that uses setInterval() to call some show_next_image() function every 5s.
It actually does work with IE, Opera, Safara, Firefox and.. partly with Google Chrome. It's not working with Google Chrome if I open a new window and directly type my website URL: it'll show the second image and stop. And with any other situation (reload, from another link, not right after opening a new window) it'll badly work: one can see the back image before the front image is shown.
Thus I'm wondering whether I've done something wrong with my JavaScript source. What I do is I use a front and a back image. When I want to show the next image, the back img source is set to the new image, and the front image is faded out while the back one is faded in through jQuery. You can check it out at http://www.laurent-carbon.com/ (in French). The two img are identified with bg1 and bg2.
var images = ["/img/IMG_0435bg.jpg", "/img/IMG_0400bg.jpg", "/img/maisonnette 2.jpg", "/img/IMG_0383bg.jpg", "/img/IMG_0409bg.jpg", "/img/IMG_0384bg.jpg"];
var idx = 1;
var waitTime = 5000; // ms
$(document).ready(function() {
$("#bg2").hide();
$.timer(waitTime, load_next);
$.preLoadImages(images);
});
function load_next(timer) {
var toshow = images[idx];
idx++;
idx %= images.length;
back_image().attr('src', toshow);
swap_images();
}
function front_image() {
return (idx % 2 == 0) ? $("#bg1") : $("#bg2");
}
function back_image() {
return (idx % 2 == 0) ? $("#bg2") : $("#bg1");
}
function swap_images() {
back_image().fadeOut('slow');
front_image().fadeIn('slow');
}
Thanks,
Ceylo
Ok I've worked out a solution .... without the use of plugins.
Demo
http://jsfiddle.net/morrison/PvPXM/9/show
source
http://jsfiddle.net/morrison/PvPXM/9/
This approach is a lot cleaner and removes the problem I had while viewing your page in chrome: the animation getting out of sync and flashing.
The only thing you have to do in the HTML is wrap the two images in a <div id="fadeBox" style="position:relative"></div>
$(function() {
var images = [
"http://www.laurent-carbon.com/img/IMG_0435bg.jpg",
"http://www.laurent-carbon.com/img/IMG_0400bg.jpg",
"http://www.laurent-carbon.com/img/maisonnette 2.jpg",
"http://www.laurent-carbon.com/img/IMG_0383bg.jpg",
"http://www.laurent-carbon.com/img/IMG_0409bg.jpg",
"http://www.laurent-carbon.com/img/IMG_0384bg.jpg"
];
var idx = 1;
var max = images.length;
var easing = "swing";
var waitTime = 5000; // ms
var fadeTime = 2000; // ms
var fadeShow = function(fadeTime, fadeDelay) {
var $topImage = $("#fadeBox img:last");
$topImage.fadeTo(fadeDelay, 1, function() {
$topImage.fadeTo(fadeTime, 0, easing, function() {
$topImage
.fadeTo(0, 1)
.insertBefore("#fadeBox img:first")
.attr("src", images[++idx == max ? idx = 0 : idx]);
fadeShow(fadeTime, fadeDelay);
});
});
};
fadeShow(fadeTime, waitTime);
});
Hope this helps
PS thanks to Levi for cleaning the code up a bit.
Answer: http://jsfiddle.net/morrison/RxyZY/
Notes:
You are trying to reinvent the wheel. You are creating a simple slideshow. There are numerous plugins to do exactly this and much more. I used jQuery cycle in my example, which is extremely customizable.
You should wrap your stuff up in a function, creating an expression. In my example, the (function($){}(jQuery)) is what does the trick. It scopes your variables to the function, rather than the global namespace.