Add different classes to VERTICAL or HORIZONTAL img - javascript

I want to style differently the images if they are vertical or hotizontal.
I'm playing around with this code but it's not working. Any ideas?
JAVASCRIPT
(function() {
var orientation,
img = new Image();
img.onload = function () {
if (img.naturalWidth > img.naturalHeight) {
$(img).addClass('landscape');}
else (img.naturalWidth < img.naturalHeight) {
$(img).addClass('portrait');}
})();
CSS
img {max-width:500px;}
.landscape {max-width: 750px;}
.portrait {max-width: 500px;}

I've just created short codepen here to show you my way of working with images:
codepen link
HTML:
<img src="https://pixabay.com/static/uploads/photo/2014/07/27/20/29/landscape-403165_960_720.jpg" />
<img src="https://s-media-cache-ak0.pinimg.com/736x/f5/a0/62/f5a0626a80fe6026c0ac65cdc2d8ede2.jpg" />
CSS:
.landscape {max-width: 750px;}
.portrait {max-width: 500px;}
JS:
window.onload = function () {
var images = document.getElementsByTagName('img');
for( var i=0; i<images.length;i++){
if (images[i].naturalWidth > images[i].naturalHeight) {
$(images[i]).addClass('landscape');
}
else{
if(images[i].naturalWidth < images[i].naturalHeight) {
$(images[i]).addClass('portrait');
}
}
}
}

You cannot use condition with else part of if-else statement. Use the following code structure:
img.onload = function () {
if (condition) {
// if above condition is true then do this ...
} else {
// otherwise do this ...
}
});
var images = $('.img img');
images.load(function() {
if (this.naturalWidth > this.naturalHeight) {
$(this).addClass('landscape');
} else {
$(this).addClass('portrait');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="img">
<img src="http://www.w3schools.com/html/pic_mountain.jpg" alt="Image Description">
</div>

Related

HTML How to change image onClick

I'm trying to have an image that changes when clicked: when image 1 is clicked, change to image 2, when image 2 is clicked change to image 3 and when image 3 is clicked it changes to image 1.
<p>
<img alt="" src="assets/img1.png"
style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "assets/img1.png")
{
document.getElementById("imgClickAndChange").src = "assets/img2.png";
}
else if (document.getElementById("imgClickAndChange").src == "assets/img2.png")
{
document.getElementById("imgClickAndChange").src = "assets/img3.png";
}
else if(document.getElementById("imgClickAndChange").src == "assets/img3.png"){
document.getElementById("imgClickAndChange").src = "assets/img1.png"
}
Clean and optimal solution in my opinion. As the users before said. It is good to use array to held the images paths.
var images = ["https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&h=350", "https://i2.wp.com/beebom.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg?resize=640%2C426", "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350"]
var imgState = 0;
var imgTag = document.getElementById("imgClickAndChange");
imgTag.addEventListener("click", function (event) {
imgState = (++imgState % images.length);
event.target.src = images[imgState];
});
Solution
There were a lot of syntax errors in your code. I cleaned them up in a codepen here where you can see that your basic logic was correct. Though, as other users pointed out, there are more elegant ways to solve this problem.
https://codepen.io/anon/pen/MPYgxM
HTML:
<p>
<img alt="" src="https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg"
style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
</p>
JS:
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg")
{
document.getElementById("imgClickAndChange").src = "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg";
}
else if (document.getElementById("imgClickAndChange").src == "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg")
{
document.getElementById("imgClickAndChange").src = "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg";
}
else if(document.getElementById("imgClickAndChange").src == "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg"){
document.getElementById("imgClickAndChange").src = "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg"
}
}
you can increment value on each click and update img. on base of incremented value
<img alt="" src="assets/img1.png" style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()" />
<script language="javascript">
var counter = 1;
function changeImage() {
counter > 3 ? counter = 1 : counter++;
document.getElementById("imgClickAndChange").src = "assets/img"+counter+".png";
}
</script>
Hi this is different approach.
new ClickListener() is the class used to handle your logic & dom logic
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Image click</title>
</head>
<body>
<div id="player">
</div>
<script>
class ClickListener {
constructor() {
this.rootElement = document.querySelector( "#player" );
this.element = document.createElement("img");
this.rootElement.appendChild(this.element);
this.images = ['./1.jpg', './2.jpg', './3.jpg']
this.idx = 0
this.init()
}
init() {
this.element.src = this.images[this.idx]
this.element.style.width = `400px`;
this.element.style.height = `400px`;
this.element.onclick = this.nextImage.bind(this)
}
nextImage() {
this.idx++;
if(this.idx >= this.images.length) {
this.idx = 0;
}
this.element.src = this.images[this.idx]
}
}
new ClickListener()
</script>
</body>
</html>

Setting timeOut in javascript on changing display of element

I have a simple script that hides and shows certain element on the site by changing display to either "none" or "block". I want it to be animated, meaning that elements will slowly fade-out. I'm fairly new to javascript and I know that there is setTimeout and setInterval, but I'm not sure how to use it. How can I "animate" this functions? Here is my code:
var rysunki = document.querySelectorAll(".rysunek");
var projekty = document.querySelectorAll(".projekt");
var btnAll = document.getElementById("allItems");
var btnProjekty = document.getElementById("projects");
var btnRysunki = document.getElementById("drawings");
function removeDrawings() {
var i;
for (i = 0; i < rysunki.length; i++) {
rysunki[i].style.display = "none";
};
};
function showDrawings(){
var i;
for (i = 0; i < rysunki.length; i++) {
rysunki[i].style.display = "block";
};
};
function removeProjects() {
var i;
for (i = 0; i < projekty.length; i++) {
projekty[i].style.display = "none";
};
};
function showProjects() {
var i;
for (i = 0; i < projekty.length; i++) {
projekty[i].style.display = "block";
};
};
function showAll() {
showProjects();
showDrawings();
}
btnProjekty.addEventListener("click", function(){
showProjects();
removeDrawings();
});
btnRysunki.addEventListener("click", function(){
removeProjects();
showDrawings();
});
btnAll.addEventListener("click", showAll);
Is it even possible? Should I add something with opacity of the elements I'm hiding?
No jQuery please, only Vanilla JS.
Edit:
As requested, here is the HTML. Basically there are 2 different elements:
<figure class="projects-panel__item col-md-3 projekt">
<img src="img/1.jpg" alt="" />
</figure>
<figure class="projects-panel__item col-md-3 rysunek">
<img src="img/1.jpg" alt="" />
</figure>
Heres an simple example of how to do it with mix of JS and CSS.
In JS I am just changing class of container, in response to button click.
In CSS I've defined transition: opacity (this is how stuff is being animated) on .projects and .drawings
I've also added two classes which will modify value of opacity on those two classes above.
Feel free to ask questions if You do not understand something.
const container = document.querySelector('#container')
const showDrawings = () => {
container.classList.remove('showProjects')
container.classList.add('showDrawings')
}
const showProjects = () => {
container.classList.remove('showDrawings')
container.classList.add('showProjects')
}
const showAll = () => {
container.classList.add('showDrawings')
container.classList.add('showProjects')
}
document.querySelector('#drawingsButton').addEventListener('click', showDrawings)
document.querySelector('#projectsButton').addEventListener('click', showProjects)
document.querySelector('#allButton').addEventListener('click', showAll)
.drawings,
.projects {
display: inline-block;
width: 200px;
height: 200px;
opacity: 0;
transition: opacity .3s .1s;
}
.drawings {
background: red;
}
.projects {
background: blue;
}
.showDrawings .drawings {
opacity: 1;
}
.showProjects .projects {
opacity: 1;
}
<div id="container">
<div class="drawings"></div>
<div class="projects"></div>
</div>
<button id="drawingsButton">Drawings</button>
<button id="projectsButton">Projects</button>
<button id="allButton">All</button>

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.

jQuery delay fadeIn

I have a javascript/jquery slideshow but I want to remove the somewhat long blank nothingness in between the fadein and fadeout images. I tried using a small delay because by default it still had a blank pause but that didn't work, any idea?
jsfiddle: https://jsfiddle.net/jzhang172/s624zn7d/1/
var imagesArray = ["http://assets.pokemon.com/assets/cms2/img/pokedex/full//007.png",
"http://assets.pokemon.com/assets/cms2/img/pokedex/full/001.png",
"https://assets.pokemon.com/static2/_ui/img/account/sign-up.png",
"http://static.giantbomb.com/uploads/scale_small/0/6087/2438704-1202149925_t.png",
"http://static.giantbomb.com/uploads/scale_small/0/6087/2438704-1202149925_t.png"];
function preloadImg(pictureUrls, callback) {
var i, j, loaded = 0;
var imagesArray = [];
for (i = 0, j = pictureUrls.length; i < j; i++) {
imagesArray.push(new Image());
}
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback(imagesArray);
}
};
img.src = src;
}(imagesArray[i], pictureUrls[i]));
}
};
function roll(imagesArray, currentPos){
var slide = $('.parallax-mirror').find('img').attr('src', imagesArray[currentPos].src);
slide.fadeIn(2000, function() {
slide.fadeOut(1500, function() {
currentPos++;
if(currentPos >= imagesArray.length){
currentPos = 0;
}
roll(imagesArray, currentPos);
});
});
}
$(function () {
preloadImg(imagesArray, function (imagesArray) {
roll(imagesArray, 0, 3);
});
});
.featured-wrapper {
height: 500px;
width: 100%;
overflow: hidden;
}
.things {
font-size: 50px;
height: 500px;
width: 100%;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parallax.js/1.4.2/parallax.min.js"></script>
<div class="featured-wrapper" data-parallax="scroll" data-image-src="http://assets.pokemon.com/assets/cms2/img/pokedex/full//007.png">
</div>
<div class="things">I'm the stuff underneath</div>
You should use an opacity animation with an easing that fits your needs. You can use jquery ui easings

Javascript Images Resize

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;

Categories