Javascript Images Resize - javascript

I want to resize images depend on its size in CSS with JS function which get all images in the div but i am facing problems with getelement by tagname which i have to set the images styles into the img HTML tag or its never work , in this test project its easy to do but in my real one there is many images into this div and many pages so here the function and its HTML
<script type="text/javascript">
function x() {
var yourdiv = document.getElementById('test');
var yourImgs = yourdiv.getElementsByTagName('img');
for (var i = 0; i < yourImgs.length; i++) {
if (yourImgs[i].style.height == '1000px' && yourImgs[i].style.width == '1000px')
{
yourImgs[i].style.height = '700px';
yourImgs[i].style.width = '800px';
}
else
{
yourImgs[i].style.height = '400px';
yourImgs[i].style.width = '300px';
}
}
}
window.onload= x;
</script>
</head>
<body>
<div id="test">
<img alt='' class="test_img" style="height:1000px;width: 1000px;" src='imges/book1.jpg' />
<img alt='' class="test_img" style="height:1000px;width: 1000px;" src='imges/book2.jpg' />
</div>

Ignore style and just check for height and width like in this example:
http://jsfiddle.net/5yjfy/2/
function x() {
var yourdiv = document.getElementById('test');
var yourImgs = yourdiv.getElementsByTagName('img');
for (var i = 0; i < yourImgs.length; i++) {
if (yourImgs[i].height == 1000 && yourImgs[i].width == 1000)
{
yourImgs[i].style.height = '700px';
yourImgs[i].style.width = '800px';
}
else
{
yourImgs[i].style.height = '400px';
yourImgs[i].style.width = '300px';
}
} } window.onload= x;

Related

How do I get the slideshow to disappear after one cycle through (javascript)

this intro slideshow works so far, it starts automatically when you load the webpage and cycles through the 4 photos. But I want the slideshow to disappear (to reveal the website homepage underneath) after it has cycled through the 4 photos only once, but need some help how to proceed forward.
<!DOCTYPE html>
<head>
</head>
<body>
<div id="slideshow">
<img id="pic" width="100%" height="auto" alt="Icon" src="one.jpg">
</div>
<script>
var i, imgs, pic;
function rotate() {
pic.src = imgs[i];
(i === (imgs.length - 1)) ? (i = 0) : (i++);
setTimeout(rotate, 1000);
}
function init() {
pic = document.getElementById("pic");
imgs = ["one.jpg", "two.jpg", "three.jpg", "four.jpg"];
var preload = new Array();
for (i = 0; i < imgs.length; i++) {
preload[i] = new Image();
preload[i].src = imgs[i];
}
i = 0;
rotate();
}
document.addEventListener("DOMContentLoaded", init, false);
</script>
</body>
</html>
var count = 0
function rotate() {
pic.src = imgs[i];
(i === (imgs.length - 1)) ? (i = 0) : (i++);
if (count < imgs.length) {
count++;
setTimeout(rotate, 1000);
} else {
document.getElementById("slideshow").style.display = 'none';
}
}
Hi,
you have to count your number of slides. Afterwards just check if you already finished.
greetings
<!DOCTYPE html>
<head>
</head>
<body>
<div id="slideshow">
<img id="pic" width="100%" height="auto" alt="Icon" src="one.jpg">
</div>
<script>
var i, imgs, pic;
function rotate() {
pic.src = imgs[i];
if(i<(imgs.length - 1)){
i++;
setTimeout(rotate, 1000);
}
}
function init() {
pic = document.getElementById("pic");
imgs = ["one.jpg", "two.jpg", "three.jpg", "four.jpg"];
var preload = new Array();
for (i = 0; i < imgs.length; i++) {
preload[i] = new Image();
preload[i].src = imgs[i];
}
i = 0;
rotate();
}
document.addEventListener("DOMContentLoaded", init, false);
</script>
</body>
</html>
if(i<(imgs.length - 1)){
i++;
setTimeout(rotate, 1000);
}
You need to check for how many time the rotate() method need to call.

Javascript Next and Previous images

Code is supposed to show next image when clicking on next arrow and previous image when clicked on previous arrow. It does not work though. (error occurs while assigning img.src=imgs[this.i]; it says Cannot set property 'src' of null
at collection.next) .
Javascript code :
var arr = new collection(['cake.png', 'image2.png', 'image3.png', 'image1.png']);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById('element')
this.i++;
if (this.i == imgs.length) {
this.i = 0;
}
img.src = imgs[this.i].src;
}
this.prev = function(element) {
var img = document.getElementById('element');
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i].src;
}
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
Not using jquery. I do not have enough experience in js either. Thank you for your time
You had three mistakes:
You referenced the images as img.src = imgs[this.i].src; and you just had an array of strings, not an array of objects with a src property. img.src = imgs[this.i]; is the correct way to get the URL.
You used
var img = document.getElementById('element');
when you should have used
var img = document.getElementById(element);
element is an argument coming from your onclick event. It holds the id of your image that you should be using. "element" is just a string. You try to find an element with id equal to element which doesn't exist.
Edit: You should also use < and > to represent < and >. Otherwise your HTML might get screwed up. More on that here.
var arr = new collection(['http://images.math.cnrs.fr/IMG/png/section8-image.png', 'https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg', "http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"]);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById(element);
this.i++;
if (this.i >= imgs.length) {
this.i = 0;
}
img.src = imgs[this.i];
};
this.prev = function(element) {
var img = document.getElementById(element);
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i];
};
this.next("mainImg"); // to initialize with some image
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
This is how I'd personally do it:
var myCollection = new Collection([
"http://images.math.cnrs.fr/IMG/png/section8-image.png",
"https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg",
"http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"
], "mainImg");
document.getElementById("next_btn").onclick = function() {
myCollection.next();
};
document.getElementById("prev_btn").onclick = function() {
myCollection.prev();
}
function Collection(urls, imgID) {
var imgElem = document.getElementById(imgID);
var index = 0;
this.selectImage = function() {
imgElem.src = urls[index];
};
this.next = function() {
if (++index >= urls.length) {
index = 0;
}
this.selectImage();
};
this.prev = function(element) {
if (--index < 0) {
index = urls.length - 1;
}
this.selectImage();
};
// initialize
this.selectImage();
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input id="next_btn" type='button' value='<' />
<img id='mainImg'>
<input id="prev_btn" type='button' value='>' />
</body>
</html>
Why sending string into arr.next('mainImg') function ?
your img element always have the same id, only change src.
and document.getElementById(element) is also the same img element.
html: <img id='mainImg' src="cake.png">
js: document.getElementById('mainImg')
consider img element as a container, and id is it's identifiler.
var start_pos = 0;
var img_count = document.getElementsByClassName('icons').length - 1;
var changeImg = function(direction){
pos = start_pos = (direction == "next")? (start_pos == img_count)? 0 : start_pos+1 : (start_pos == 0)? img_count : start_pos-1;
console.log(pos)
}
document.getElementById('left').onclick = function(){ changeImg("previous"); }
document.getElementById('right').onclick = function(){ changeImg("next"); }

how to onclick for pairs of images randomly in javascript?

/* egg & broke egg pair1 lite & broke lite pair2 pot & frys pair3 */
I would like to know how to make the images pair up or team up. So when you click the egg image it disappears and the broken egg appears. Then this image should also disappear then and one of the other two teams appear randomly lite click lite broke lite appears and disappears randomly and click pot it turns into frys then frys disappears and turns into a random team.
</head>
<body onLoad="setRandomImage()">
<img id="egg.png" src= "http//"onClick="setRandomImage();"/>
<img id="brokeEgg.png" src= "https://" style="display:none"/>
<img id="lite.png" src= "http://" style="display:none"/>
<img id="brokeLite.png" src= "http://" style="display:none"/>
<img id="pot.jpg" src= "https://style="display:none"/>
<img id="frys.jpg" src= "http://style="display:none"/>
<script type="text/javascript">
var myShapes= ["egg.png","brokeEgg.png","lite.png","brokeLite.png","pot.jpg","frys.jpg" ];
function setRandomImage() {
var imgElem = document.getElementById("egg.png")
imgElem.setAttribute('src',myShapes[Math.floor(Math.random()*6)]);
};
</script>
Here's a very simplified one by making use of HTML data-* attributes, but take in consideration:
The value data-image-seq attribute must be img followed by a number.
These numbers must be sequenced
Updated
jsFiddle
var imgs = document.querySelectorAll('.imgs-wrapper img'),
currentIMG = 1;
// attach click events on odd images only, egg, lite, pot, hi1, hello1
for (var i = 0; i < imgs.length; i += 2) {
addEvent(imgs[i], 'click');
}
function addEvent(element, event) {
element.addEventListener(event, function() {
var imgSeq = element.getAttribute('data-image-seq'),
nextImgSeq, nextImg, shownIMG;
imgSeq = parseInt(imgSeq.replace('img', ''), 10);
nextImgSeq = (imgSeq < imgs.length) ? (imgSeq + 1) : 1;
nextImg = 'img[data-image-seq=img' + nextImgSeq + ']';
element.style.display = 'none';
shownIMG = document.querySelector(nextImg);
shownIMG.style.display = 'block';
setTimeout(function() {
shownIMG.style.display = 'none';
showRandomImg();
}, 1000);
});
}
function showRandomImg() {
var randomIMG = returnRandomOddNum();
randomIMG = (randomIMG !== currentIMG) ? randomIMG : returnRandomOddNum();
currentIMG = randomIMG;
randomIMG = 'img[data-image-seq=img' + randomIMG + ']';
document.querySelector(randomIMG).style.display = 'block';
}
function returnRandomOddNum() {
var randomNum = Math.floor(Math.random() * imgs.length);
randomNum = (randomNum % 2 != 0) ? randomNum : randomNum + 1;
return randomNum;
}
.imgs-wrapper { position: relative; }
.imgs-wrapper { cursor: pointer; }
.hide-me { display: none; }
<div class="imgs-wrapper">
<img data-image-seq="img1" src="//dummyimage.com/150x50?text=egg">
<img data-image-seq="img2" src="//dummyimage.com/150x50?text=broke egg" class="hide-me">
<img data-image-seq="img3" src="//dummyimage.com/150x50?text=lite" class="hide-me">
<img data-image-seq="img4" src="//dummyimage.com/150x50?text=broke light" class="hide-me">
<img data-image-seq="img5" src="//dummyimage.com/150x50?text=pot" class="hide-me">
<img data-image-seq="img6" src="//dummyimage.com/150x50?text=frys" class="hide-me">
<img data-image-seq="img7" src="//dummyimage.com/150x50?text=Hi1" class="hide-me">
<img data-image-seq="img8" src="//dummyimage.com/150x50?text=Hi2" class="hide-me">
<img data-image-seq="img9" src="//dummyimage.com/150x50?text=Hello1" class="hide-me">
<img data-image-seq="img10" src="//dummyimage.com/150x50?text=Hello2" class="hide-me">
</div>
Use this function to toggle the visibility of two elements on click:
function bindToggleVisibilityOnClick(firstElemId, secondElemId) {
var firstElement = document.getElementById(firstElemId);
var secondElement = document.getElementById(secondElemId);
firstElement.onclick = function() { toggleVisibility(firstElement, secondElement); };
secondElement.onclick = function() { toggleVisibility(secondElement, firstElement); };
}
function toggleVisibility(checkElem, otherElem){
// If target is invisible
if (checkElem.style.display == "none"
//|| checkElem.style.visibility == "hidden"
) {
checkElem.style.display = "block";
// checkElem.style.visibility = "visible";
otherElem.style.display = "none"
// otherElem.style.visibility = "hidden";
}
else {
otherElem.style.display = "block";
checkElem.style.display = "none"
// checkElem.style.visibility = "hidden";
}
};
bindToggleVisibilityOnClick("egg", "brokenEgg");
#egg { display: block; }
#brokenEgg { display: none; }
<div id="egg"><p>hi</p></div>
<div id="brokenEgg"><p>hi2</p></div>
Use as such:
// Should now toggle visibility on click
bindToggleVisibilityOnClick("egg", "brokenEgg");
Also note I've left lines to toggle visibility instead of display, which will hide the element but leave the space that it takes up.
EDIT: If you want it to change once and not revert, comment out that second binding in the function as follows:
function bindToggleVisibilityOnClick(firstElemId, secondElemId) {
var firstElement = document.getElementById(firstElemId);
var secondElement = document.getElementById(secondElemId);
firstElement.onclick = function() { toggleVisibility(firstElement, secondElement); };
//secondElement.onclick = function() { toggleVisibility(secondElement, firstElement); };
}
function toggleVisibility(checkElem, otherElem){
// If target is invisible
if (checkElem.style.display == "none"
//|| checkElem.style.visibility == "hidden"
) {
checkElem.style.display = "block";
// checkElem.style.visibility = "visible";
otherElem.style.display = "none"
// otherElem.style.visibility = "hidden";
}
else {
otherElem.style.display = "block";
checkElem.style.display = "none"
// checkElem.style.visibility = "hidden";
}
};
bindToggleVisibilityOnClick("egg", "brokenEgg");
#egg { display: block; }
#brokenEgg { display: none; }
<div id="egg"><p>hi</p></div>
<div id="brokenEgg"><p>hi2</p></div>
If I understood the question correctly you ca use an object instead of an array for myShapes.
var myShapes = {
"egg.png": "brokeEgg.png",
...
}
so when you click an image you can find the paired one.

Why doesn't this mouseover/rollover work?

I have 3 images (pic1, pic2, pic3) that on click of the div ID change to (pic4, pic5, pic6). All this works fine but I need to put in a mouseover command that when hovering over pic2, it changes to pic 7 and on mouseout it goes back to pic 2. I am unsure as to why this part of my code isn't working, is it a syntax error? The two functions I am trying to use to do this are "rolloverImage" and "init".
HTML
<div id="content1">
<img src="pic1.jpg" alt="pic1"/>
<img src="pic2.jpg" alt="pic2" id="pic2"/>
<img src="pic3.jpg" alt="pic3"/>
</div>
Javascript
var g = {};
//Change background colors every 20 seconds
function changebackground() {
var backColors = ["#6AAFF7", "#3AFC98", "#FC9B3A", "#FF3030", "#DEDEDE"];
var indexChange = 0;
setInterval(function() {
var selectedcolor = backColors[indexChange];
document.body.style.background = selectedcolor;
indexChange = (indexChange + 1) % backColors.length;
}, 20000);
}
function rolloverImage(){
if (g.imgCtr == 0){
g.pic2.src = g.img[++g.imgCtr];
}
else {
g.pic2.src = g.img[--g.imgCtr];
}
}
function init(){
g.img = ["pic2.jpg", "pic7.jpg"];
g.imgCtr = 0;
g.pic2 = document.getElementById('pic2');
g.pic2.onmouseover = rolloverImage;
g.pic2.onmouseout = rolloverImage;
}
window.onload = function() {
var picSets = [
["pic1.jpg", "pic2.jpg", "pic3.jpg"],
["pic4.jpg", "pic5.jpg", "pic6.jpg"],
];
var currentSetIdx = 0;
var contentDiv = document.getElementById("content1");
var images = contentDiv.querySelectorAll("img");
refreshPics();
contentDiv.addEventListener("click", function() {
currentSetIdx = (currentSetIdx + 1) % picSets.length;
refreshPics();
});
function refreshPics() {
var currentSet = picSets[currentSetIdx];
var i;
for(i = 0; i < currentSet.length; i++) {
images[i].src = currentSet[i];
}
}
changebackground();
init();
}

javascript not working on button as expected

I'm trying to connect previous and fwd buttons to a gallery and I want the previous button to be hidden on first image of the gallery but javascript doesn't seem to be working at all.
Javascript
var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function next() {
imgCount++ ;
document.getElementById("gallery").src = imageGallery[imgCount] ;
}
function previous() {
imgCount--;
document.getElementById("gallery").src = imageGallery[imgCount] ;
}
if(document.getElementById("gallery").getAttribute("src") == "1.png")
{
document.getElementById("previous").style.visibility = 'hidden';
}
else
{
document.getElementById("previous").style.visibility = 'visible';
}
HTML
<div id="img">
<img id="gallery" src="1.png" style="height:420px; width:744px" >
<div id="imgNav">
<a id="previous" href onclick="previous(); return false;">previous</a>
<span style="color:#666; font-size:0.9em"> | </Span>
<a id="next" href onclick="next(); return false;">next</a>
</div>
</div>
Actually the logic is if 'src' attribute of id 'gallery' is '1.png' then 'visibility' of element with id 'previous' is 'hidden' else not but doesn't seem to be working. Can anyone help figuring it out.
You're probably trying to check on an image that's not totally loaded yet. Did you remember to place your code to run just when the page is fully loaded (in case it's placed in the page headers - you didn't mention whether it is or not)?
UPDATED
var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function checkNav() {
var previousLnk = document.getElementById("previous");
var nextLnk = document.getElementById("next");
previousLnk.style.visibility = imgCount == 0 ? 'hidden' : 'visible';
nextLnk.style.visibility = imgCount >= (imageGallery.length - 1) ? 'hidden' : 'visible';
}
function setImg() {
var gallery = document.getElementById("gallery");
gallery.src = imageGallery[imgCount];
}
function next() {
imgCount++;
setImg();
checkNav();
}
function previous() {
imgCount--;
setImg();
checkNav();
}
window.onload = function () {
checkNav();
}
Demo: http://jsfiddle.net/N7V9E/

Categories