Change attributes of image in a new window - javascript

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

Related

Finding the image count in a web page

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

Changing a picture by clicking on it with Javascript

This is my first ever question on here and I figure it must have a simple answer but it's frustrated me for a while, especially since I'm new to Javascript. So I have many images and would like to change to the next one by clicking on it on the webpage, starting with a certain image, obviously. Now I could do this with nested if else statements but if you have many images you get too many ones nested into each other and it can get too complex so I figured there must be a simpler way of doing it. Here's an example of the code I had:
function changeImage()
{
var image=document.getElementById("mainImage")
if (image.src.match("image1.jpg"))
{
image.src="image2.jpg";
}
else if (image.src.match("image2.jpg"))
{
image.src="image3.jpg";
}
else
{
if (image.src.match("image3.jpg"))
{
image.src="image4.jpg";
}
else
{
image.src="image1.jpg";
}
}
}
So you can see it's not the best way to do it. I tried to do it with a switch statement but I couldn't either (and would appreciate it if someone told me if it could be done with one and how). As a last try I tried this but for some reason it jumps from image1 to image4 at once:
function changeImage()
{
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
var myImage = document.getElementById("mainImage")
for (i=0; i < images.length; i++)
{
if (myImage.src.match(images[i]))
{
myImage.src = images[i+1]
}
}
}
So I could really appreciate some help. Thanks in advance.
Your last changeImage goes to #4 immediately because you're changing the image in the for loop which causes the check within the loop to keep being true and so it runs all the way to the last index, at which point the check finally fails. Instead, you'll want to maintain the current image index with a variable. Then, just change myImage.src to images[currentIndex + 1] on each click. Try something like below. You'll want to run showNextImage on page load and then run it once each time the image is clicked.
<script>
var currentImageIndex = 0;
//Cycle through images
showNextImage() {
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
var myImage = document.getElementById("mainImage")
myImage.src = images[currentImageIndex];
currentImageIndex++;
if(currentImageIndex >= images.length)
currentImageIndex = 0;
}
</script>

Why is my image not loading?

At http://blajeny.com I have:
jQuery('body').click(function(event_object)
{
spark(event_object.pageX, event_object.pageY);
});
function spark(x, y)
{
console.log('Spark called.');
var image_object = new Image();
image_object.onLoad = function()
{
image_object.style.position = 'absolute';
image_object.style.zIndex = 1;
image_object.style.top = y;
image_object.style.left = x;
}
image_object.src = '/img/spark.png';
}
The intended effect, at this stage, is to load an image at the X and Y where the user clicked. (I want to do other things as well, like animate it, but right now I'm trying to get the image to show up where the user clicked.)
The javaScript console shows that the handler is being called, however I am not seeing what I expect, a hazy blue circle immediately below and to the right of the point where the mouse was clicked.
What can/should I do differently so it loads a fresh image below and to the right of the clicked coordinates?
Thanks,
As far as I know, the onLoad should be onload
var image_object = document.createElement('img');
image_object.onload = function() { // Note the small onload
// your code
}
// Also, append the image_object to DOM
document.body.appendChild(image_object);
I don't see you appending the image to DOM that's probably why you're not seeing it
$('body').append($(image_object));
I agree, first create an element with the "img" tag, assign the src value to it, and append it to the current div (in this case its the body), like so
var imgTag = document.createElement("img");
imgTag.src = '/img/spark.png';
document.body.appendChild(imgTag);
Hope this helps.
You never append the image to the DOM, that's why you can't see it.
You can do
document.body.appendChild(image_object);
You must also replace onLoad by onload and specify the top and left position with an unit :
image_object.onload = function() {
image_object.style.position = 'absolute';
image_object.style.zIndex = 1;
image_object.style.top = '100px';
image_object.style.left = '100px';
}
Demonstration

Creating a very simple game in JS

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.

Chrome doesn't always repeat events with JavaScript setInterval()

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.

Categories