i try to créate a javascript class for zoom in and zoom out some pictures.
But all pictures of the page zoom in and zoom out. I think it's a javascript loop's problem but i cant do it.
This is my Class , someone see the problem ?
class Image {
constructor() {
this.ip = document.getElementsByClassName("image_petite");
this.images = [];
}
agrandir() {
for (let i=0; i < this.ip.length; i++) {
this.images.push(this.ip[i]);
};
console.log(this.images);
for (let j=0; j < this.images.length; j++) {
if (this.images[j].classList == "image_petite") {
this.images[j].classList.remove('image_petite');
this.images[j].classList.add('image_grande');
} else if (this.images[j].classList == "image_grande") {
this.images[j].classList.remove('image_grande');
this.images[j].classList.add('image_petite');
}
}
}
}
let image = new Image();
this.images[j].classList == "image_petite" isn't how you check to see if an element has a class. Instead, you use contains:
if (this.images[j].classList.contains("image_petite")) {
// ...
}
Separately, though, you've used a loop, which intentionally processes everything in the this.images array. It's hard to say what you should do instead without knowing what the DOM structure (loosely, the HTML) looks like, but if you're trying to handle resizing one image, you'll need to identify the image you want to resize, which nothing in that code does.
Here's a simple example using a click handler:
// This example uses event delegation
document.body.addEventListener("click", event => {
const image = event.target.closest("img");
if (image && event.currentTarget.contains(image)) {
// This is the image to enlarge or toggle
if (image.classList.contains("image_grand")) {
// Toggling it from big back to small
image.classList.remove("image_grand");
image.classList.add("image_petite");
} else {
// Making this the one big one
const big = document.querySelector(".image_grand");
if (big) {
// Make the current big one small again
big.classList.remove("image_grand");
big.classList.add("image_petite");
}
// Make this one big
image.classList.add("image_grand");
image.classList.remove("image_petite");
}
}
});
.image_petite {
width: 75px;
height: 75px;
}
.image_grand {
width: 150px;
height: 150px;
}
<div>
<img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080 ?text=1">
</div>
<div>
<img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080 ?text=2">
</div>
<div>
<img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080 ?text=3">
</div>
That said, I think I'd use just a single class and add/remove that class, rather than two classes.
Related
I have 3 images on my page. I have assigned eventListener to check for a click, once a click has occurred on one of the images, everything else gets blurred (including the other two images).
Any help is appreciated, thanks.
function showInfo() {
const images = document.getElementsByTagName("img");
const container = document.getElementsByClassName("container");
for (let i = 0; i < images.length; i++) {
images[i].addEventListener("click", (evt) => {
// images[i].style.
})
}
}
showInfo();
You can do it using forEach(). That means if you click on each of them, it must run the command. But don't forget that this method is only possible for more than one HTML tag. (You have 3 images).
After clicking on each element, you must write a for..in loop (modern ecmascript-edition) so you can choose all of the images and apply the blur.
const images = document.querySelectorAll('img');
images.forEach(e => {
// e here means each image, no matter which one is the purpose
e.addEventListener('click', () => {
for (let i in images) {
images[i].style.filter = 'blur(8px)';
i++;
}
})
})
img {
margin-block: 10px
}
<img src="https://picsum.photos/300/200" />
<img src="https://picsum.photos/300/200" />
<img src="https://picsum.photos/300/200" />
I have an array of URIs that represent .png elements, e.g., "./img/diamond-red-solid-1.png".
I want to assign each element of the array "gameDeck[0], gameDeck[1], etc. to div ids in HTML. Do I need to identify the elements as = SRC.IMG?
var gameDeck[];
var gameBoardCards = function () {
for (let cardArr of cardsToLoad)
gameDeck.push("./img/" + cardArr + ".png");
}
gameBoardCards();
document.addEventListener('DOM Content Loaded', function () {
gameDeck[0] = document.getElementById("card1");
gameDeck[1] = document.getElementById("card2");
etc.
});
The way I'm understanding your question is that you would like to target the divs in your HTML with ids of card1, card2, card3... card12 etc.
You would like to insert an img tag into each of these divs with the src being the URIs of the gameDeck array.
The following code achieves this. I've tested it and it works fine. Hope it helps :)
document.addEventListener('DOMContentLoaded', function () {
//iterate through the gameDeck array.
for (let x = 0;x < gameDeck.length;x++){
//create an img tag for each gameDeck element
var imgElement = document.createElement("img");
//set the source of the img tag to be the current gameDeck element (which will be a URI of a png file)
imgElement.src = gameDeck[x];
//target the div with id "card(x + 1)"
var cardID = "card" + (x + 1);
var cardElement = document.getElementById(cardID);
//append the img tag to the card element
cardElement.appendChild(imgElement);
}
//log the HTML to the console to check it
console.log(document.getElementById('body').innerHTML);
});
Here is a way that you can either insert images as background images, or as <img /> elements into the divs you are referring to:
<div id="card0" style="width: 100px; height: 100px;"></div>
<div id="card1" style="width: 100px; height: 100px;"></div>
let loadedImage = [];
function preloadImages(urls, allImagesLoadedCallback) {
let loadedCounter = 0;
let toBeLoadedNumber = urls.length;
urls.forEach(function(url) {
preloadImage(url, function() {
loadedCounter++;
console.log(`Number of loaded images: ${loadedCounter}`);
if (loadedCounter == toBeLoadedNumber) {
allImagesLoadedCallback();
}
});
});
function preloadImage(url, anImageLoadedCallback) {
img = new Image();
img.src = url;
img.onload = anImageLoadedCallback;
loadedImage.push(img);
}
}
function gameBoardCards() {
for (let i = 0; i < loadedImage.length; i++) {
document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`;
// document.getElementById(`card${i}`).appendChild(loadedImage[i]);
}
}
preloadImages([
`https://upload.wikimedia.org/wikipedia/commons/thumb/7/7d/Color_icon_green.svg/2000px-Color_icon_green.svg.png`, `https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/225px-Solid_blue.svg.png`
], function() {
console.log(`all images were loaded`);
gameBoardCards();
// continue your code
});
It may seem like a bit much for what you are trying to accomplish, but I threw in a proper image-loading handler there. The preloadImages function will handle the loading of images, that way they are properly preloaded, and can render to the DOM. Often times, we try to use images before they are properly loaded, resulting in them sometimes not being displayed, despite no errors are being thrown.
The rest of the code is straight forward, in the for loop, it loops through the existing divs and you can either use the current active line document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`; to use the loadedImage[i] image src to load that as the divs's background image. Or you can use the commented-out line directly below that document.getElementById(`card${i}`).appendChild(loadedImage[i]); to insert an <img /> element into that div. Just use either one that works for you.
You can see the code in action in this JS Fiddle demo.
Hope this helps :)
I am trying to make multiple images (3) fade in and out as parallax background. I am currently using a large animated gif which is not going to cut it due to the loading times and what I eventually need. I am trying to target a "data-background" attribute which I have done but can't seem to get the images to change. I can get it to output in the console but not the data-background. Below is the code.
Thanks!
<section id="paralax-image" style="height: 400px;" class="module-cover parallax" data-background="" data-overlay="1"
data-gradient="1">
(function () {
// The images array.
var images = ["assets2/Arcadian.jpg", "assets2/AngryPrawns.jpg", "assets2/Apricot_Smash.jpg"];
// The counter function using a closure.
var add = (function() {
// Setting the counter to the last image so it will start with the first image in the array.
var counter = images.length - 1;
return function() {
// When the last image is shown reset the counter else increment the counter.
if(counter === images.length - 1) {
counter = 0;
} else {
counter+=1;
}
return counter;
}
})();
// The function for changing the images.
setInterval(
function() {
var section = document.getElementById("paralax-image");
section.getAttribute("data-background");
section.setAttribute('data-background', images[add()]);
console.log(images[add()]);
}
, 3000);
})();
First of all, attributes that have "data-" in front of them are only used to store some custom data on elements. Those attributes do not influence the appearance/behaviour of your app in any way unless you use them in your JS/CSS.
So, in your code, you are setting the data-background attribute on your section. The code is working correctly and if you look into the inspector, you can actually see that that attribute's value is changing as expected.
The next step for you would be to display the images that you set in your data-background attribute - either using JS or CSS.
Unfortunately, for now, it's not possible to grab the background URL from attribute value in CSS as described in the top-voted answer here: Using HTML data-attribute to set CSS background-image url
However, you can still manually set the CSS background-image property using JavaScript based on the "data-" property.
// The images array.
const images = ["https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg?auto=compress&cs=tinysrgb&h=350", "https://images.pexels.com/photos/531880/pexels-photo-531880.jpeg?auto=compress&cs=tinysrgb&h=350", "https://images.unsplash.com/photo-1530482817083-29ae4b92ff15?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=44f4aebbd1e1371d5bf7dc22016c5d29&w=1000&q=80"];
const imagesSwitcher = () => {
const getCounter = () => {
// Setting the counter to the last image so it will start with the first image in the array.
let counter = images.length - 1;
return () => {
// When the last image is shown reset the counter else increment the counter.
if(counter === images.length - 1) {
counter = 0;
} else {
counter += 1;
}
return counter;
}
}
const counter = getCounter();
const updateBackground = () => {
const section = document.getElementById("paralax-image");
section.style.background = `url(${images[counter()]}) no-repeat`;
};
updateBackground();
setInterval(() => updateBackground(), 3000);
};
imagesSwitcher();
.dynamic-background {
display: block;
width: 500px;
height: 200px;
background-size: 100%;
}
<div>
<section id="paralax-image" class="dynamic-background" style="height: 400px;" class="module-cover parallax" data-background="" data-overlay="1" data-gradient="1">
</section>
</div>
The thing is - in this case, you don't even actually need this data-background property. You can simply switch background image using JS.
Now, it's not very clear what you meant by parallax in your case. In case you actually meant parallax background like in here http://jsfiddle.net/Birdlaw/ny8rqzu5/, you would need to take a different approach overall. Please comment if you need any help with this.
I'm new to coding and am trying to enlarge an image onclick and then un-enlarge an image onclick, using JavaScript. I've tried using jQuery but jQuery doesn't seem to work so I'm simply using JavaScript.
This is the JavaScript:
var myImg1 = document.getElementById('myImg1')
var myImg2 = document.getElementById('myImg2')
var myImg3 = document.getElementById('myImg3')
myImg1.onclick = function() {
if (myImg1.style.height = '100px') {
myImg1.style.height = '1000px'
return
} else {
myImg1.style.height = '100px'
return
}
}
The image has the class assigned 'i' in HTML and CSS, which sets the width as 100px.
The code does successfully enlarge the image to 1000px but it doesn't un-enlarge.
I've tried quite a few different methods, but mostly with jQuery and I can't get jQuery to work.
you need to use 2 equal signs to compare two things, one equal sign means you are trying to set a value for that variable.
if (myImg1.style.height == '100px') {
myImg1.style.height = '1000px'
// return
}
as Pato Salazar mentioned in the comments the return statement isn't needed.
JavaScript:
var myImg1 = document.getElementById('Img1');
myImg1.onclick = function() {
if (myImg1.style.height == '1000px') {
myImg1.style.height = '100px';
} else {
myImg1.style.height = '1000px';
}
}
OR
jQuery:
jQuery(document).ready(function() {
jQuery('#Img1').click(function() {
jQuery('#Img1').toggleClass('img1_1000px');
});
});
Both work. If you need jQuery, use to write < img src="Img1.jpg" id="Img1" style="height: 100px;" > and .img1_1000px { height: 1000px!important; } in style.
I hope I helped you.
I am writing a code that creates a memory game. I need to make it so that when my mouse is over a block it shades that block to a different color. I am writing the code in javascript. Whenever I try something is just says string is not a function. I am writing in khan academy and the code is mouseOver="this.color='black'"; Can anyone please help me?
draw = function() {
if (delayStartFC && (frameCount - delayStartFC) > 30) {
for (var i = 0; i < tiles.length; i++) {
if (!tiles[i].isMatch) {
tiles[i].drawFaceDown();
}
}
flippedTiles = [];
delayStartFC = null;
// commented no loop because the timer stops working if this is enabled.
mouseOver="this.color='black';"
// noLoop();
}
You need to use this.style.backround='color' instead of this.color='color'. Try the below code:
<div style="background:red;" onmouseover="this.style.background='blue';" onmouseout="this.style.background='red'">Content</div>
When you put the code inline, it can get messy, so extracting it would be helpful like below:
The "selector" is whatever div or class or id you want to turn black on the mouse hover action.
$('selector').hover(function() {
$(this).css('background-color', 'black');
});
One solution could be:
<div onmouseover="Color(this,'black')"></div>
function Color(obj, color){
obj.style.background=color;
}
hope it's useful!
I'm assuming that you are looking at the "Project:Memory++" page, so I'll work from there.
If you look at the function above draw, it's called mouseClicked, you'll notice that it has a way of checking if a card is under the mouse:
mouseClicked = function() {
for (var i = 0; i < tiles.length; i++) {
if (tiles[i].isUnderMouse(mouseX, mouseY)) { //this line designates a tile under the mouse
// draw the tile, tiles[i], with a color over it.
After you've found which tile to color, you'll need to write a function to change it, either by changing the image that the tile shows or by giving it an overlay. There are a few good ideas in the other threads, but I would stick with what you've been given during your other projects on Khan Academy.
I usually put events like mouseover in event listeners, rather than in the HTML mouseover attribute. If you're looking to do it in pure JavaScript, try this:
document.getElementById("test").addEventListener("mouseover",function(e){e.target.style.backgroundColor = "#000";});
document.getElementById("test").addEventListener("mouseout",function(e){e.target.style.backgroundColor = "#FFF";});
You can also just accomplish this with CSS:
#test {
background-color: #FFF;
}
#test:hover {
background-color: #000;
}