How to alert when element in a list is clicked? - javascript

function whatami(img){
console.log(img.key);
}
let animals = ["frog","frog","sheep","sheep","snail","snail","mouse","mouse","bat","bat","walrus",
"walrus","giraffe","giraffe","zebra","zebra","dog","dog","octopus","octopus","hippo",
"hippo","camel","camel","pig","pig","rhino","rhino","rooster","rooster","panda","panda",
"turtle","turtle","raccoon","raccoon","polar bear","polar bear","lion","lion","bison",
"bison","orca","orca","snake","snake","shark","shark","toucan","toucan","butterfly",
"butterfly","anteater","anteater","seal","seal","armadillo","armadillo","rooster","rooster"]
var array = shuffle(animals);
let images = array.map(image => {
return <img onClick = {whatami(image)} key={image} src={"/animalgameback.jpg"} alt="" className="img-responsive"/>
});
return (
<div>
<div>
{images}
</div>
</div>
)
}
}
I have this list of images and I need a way to find which one is clicked when I press one of them. How do I do this?

The click must receive a callback function. Try writing the onClick with a arrow function like this
onClick = { () => { whatami(image)} }

I would write ()=>{whatami(image)} instead of whatami(image). LEt me know if it works.

Related

Why i need to click twice to call my function

i need your help please, my function works but i need to click twice to call it. i tried a lot of options but never works fine (sorry for my english im french)
function deleteItem() {
let products = document.querySelectorAll(".deleteItem");
for (let product of products) {
product.addEventListener("click", (e) => {
let id = e.target.getAttribute("dataid");
let color = e.target.getAttribute("datacolor");
let deleteItem = basket.find(
(element) => element.id == id && element.color == color
);
console.log(deleteItem);
basket = basket.filter((item) => item != deleteItem);
localStorage.setItem("basket", JSON.stringify(basket)),
(window.location.href = "cart.html");
});
}
}
deleteItem();
<div class="cart__item__content__settings__delete">
<p class="deleteItem" onclick="deleteItem()" dataid="${id}" datacolor="${color}">Supprimer</p>
</div>
Testing your code, it works on first click.
dont use onclick and eventlistener together, as you will be capturing multiple clicks
This is not an answer, but working code.
function deleteItem() {
let products = document.querySelectorAll(".deleteItem");
for (let product of products) {
product.addEventListener("click", (e) => {
let id = e.target.getAttribute("dataid");
let color = e.target.getAttribute("datacolor");
alert("i am clicked")
});
}
}
deleteItem();
<div class="cart__item__content__settings__delete">
<p class="deleteItem" dataid="5" datacolor="blue">Supprimer</p>
</div>

forEach executes only once javascript

I am using a forEach method to add an event listener to each button, everything is working the first time, the function is calling the filterElements function as wanted BUT when i try to click a second time the code doesen't respond, could it be because of my HTML collection that I am transforming to an Array using Array.from or what could it be ?
function filterPhotograpsIndividualTages(dataJson) {
const individualTags = Array.from(document.getElementsByClassName('individual-tags'));
individualTags.forEach(btn => btn.addEventListener('click', () => { //this is the forEach method
/*onClick clear the old HTML of photographersDiv and call
the function filterElements to execute his block code!*/
document.getElementById('container').innerHTML = "";
filterElements(dataJson, btn);// function is invoked here
}))
};
// this function is being called inside of the filterPhotograpsIndividualTages function
function filterElements(dataJson, btn){
dataJson.photographers.forEach(photographe => {
if(photographe.tags.indexOf(btn.id) != -1) {
const photographersDiv = document.getElementById('container');
const div = document.createElement("div");
div.innerHTML = `
<div class="photographerContainer">
<a href="photographers.html?id=${photographe.id}">
<div class="portraitBox">
<img src="${photographe.portrait}" alt="photo">
</div>
<h1 class="name">${photographe.name}</h1>
</a>
<p class="city">${photographe.city}, ${photographe.country}</p>
<p class="tagline">${photographe.tagline}</p>
<p class="price">${photographe.price}€/jour</p>
<p class="tags">${photographe.tags.map(tag => `<button id=${tag} class="tag individual-tags">#${tag}</button>`).join(" ")}</p>
</div>
`
photographersDiv.appendChild(div);
}})
};
When you add event like this, it only binding to DOM you have selected with getElementsByClassName not with the one re-add after delete
Instead you should bind whole document and check event's target
document.addEventListener('click', function(event) {
if (event.target.classList.contains('your_class')) {
Function();
}
});

how to fetch a new image from api after one click vanilla.js

I'm trying to figure out a better way to fetch a new image when clicking my button.
here is my code:
function getPizzaHtml(pizza) {
return `
<div class="header">Random Pizzas 🍕</div>
<button id="show-pizza-btn">Click Me</button>
<div class="pizza-image">
<img class="pizza-images" style="display: none" src="${pizza.image}"/>
</div>
`
}
getPizzaImg().then(pizza => {
console.log(pizza)
document.body.innerHTML = getPizzaHtml(pizza);
let pizzaBtn = document.getElementById('show-pizza-btn');
pizzaBtn.addEventListener('click', (e) => {
let pizzaImg = document.querySelector('.pizza-images');
if(pizzaImg.style.display === 'none') {
pizzaImg.style.display = 'inline'
} else {
window.location.reload();
}
})
})
with the if-statement, I can fetch a new image since it reloads the page and so reloads the fetch. But, in order for it to appear, I have to click it twice.
I appreciate all advice and help!
You can change pizzaImg.src to change the image. You can change your event listener to something like this:
pizzaBtn.addEventListener('click', (e) => {
let pizzaImg = document.querySelector('.pizza-images');
if(pizzaImg.style.display === 'none') {
pizzaImg.style.display = 'inline'
} else {
getPizzaImg().then(newPizza => pizzaImg.src = newPizza.image)
}
})

src not changing on else if part of if/else statement

I have created a function which is used in an event listener function so when the user clicks the left arrow icon on the webpage, a different character image is displayed. The first click works fine and the image is changed, however on the second click, nothing happens. I can't figure out why as from what I can see, the condition of the 'else if' of the statement is true so therefore the src code should change accordingly and change the image.
There are no error messages in the console.
Here is the Event listener:
document.querySelector(".left").addEventListener("click", () => {
leftArrow();
});
Here is the leftArrow function:
leftArrow: () => {
if (document.querySelector(DOMStrings.characterImg).src = characters[0]) {
document.querySelector(DOMStrings.characterImg).classList.add("boris");
document.querySelector(DOMStrings.characterImg).src = characters[1];
const el = document.querySelector(DOMStrings.characterImg);
console.log(el);
} else if (document.querySelector(DOMStrings.characterImg).src = characters[1]) {
document.querySelector(DOMStrings.characterImg).classList.remove("boris");
document.querySelector(DOMStrings.characterImg).src = characters[0];
const el = document.querySelector(DOMStrings.characterImg);
console.log(el);
}
Here is where the images are stored:
const characters = ["Resources/Images/trump.png", "Resources/Images/boris.png"];
Here is where the DOM strings are stored:
const DOMstrings = {
characterImg: ".character-img"
}
Lastly, here is the relevant html:
<div class="character-select">
<ion-icon class="left" name="arrow-dropleft-circle"></ion-icon>
<ion-icon class="right" name="arrow-dropright-circle"></ion-icon>
<img class="character-img" src="Resources/Images/trump.png">
</div>
function myFunction() {
document.getElementById("myImg").src = "https://www.w3schools.com/jsref/hackanm.gif";
}
function myFunctionbygeneric(){
document.querySelector(".test").src = "https://www.w3schools.com/jsref/hackanm.gif";
}
function myFunctionbygenericid(){
document.querySelector("#myImg").src = "https://www.w3schools.com/jsref/compman.gif";
}
<img id="myImg" class="test" src="https://www.w3schools.com/jsref/compman.gif" width="107" height="98">
<button onclick="myFunction()">click here</button>
<button onclick="myFunctionbygenericid()">Query selector by id</button>
<button onclick="myFunctionbygeneric()">Query selector</button>
Use can use like this
let myImage = document.querySelector('img');
myImage.onclick = function() {
let mySrc = myImage.getAttribute('src');
if(mySrc === 'https://www.w3schools.com/jsref/compman.gif') {
myImage.setAttribute ('src','https://www.w3schools.com/jsref/hackanm.gif');
} else {
myImage.setAttribute ('src','https://www.w3schools.com/jsref/compman.gif');
}
}
<img src="https://www.w3schools.com/jsref/hackanm.gif" />

Two function in onMouseOver React.js

render: function() {
return (
<td>
<img src={this.props.image.path} width="40" height="40" id={this.props.image.id}
onMouseOver={()=>document.getElementById(this.props.image.id).height="80", ()=>document.getElementById(this.props.image.id).width="80"}
onMouseOut={()=>document.getElementById(this.props.image.id).height="40", ()=>document.getElementById(this.props.image.id).width="40"}/>
</td>
);
}
I want to change image size when onMouseOver but it only width changed.
How can I use two function in onMouseOver. Thank you.
use it like this:
onMouseOver={() => {
document.getElementById(this.props.image.id).height = "80";
document.getElementById(this.props.image.id).width = "80";
}
}
But better to use function
onMouseOver={this.someFunction}
someFunction = () => {
document.getElementById(this.props.image.id).height = "80";
document.getElementById(this.props.image.id).width = "80";
}
Easy one. You can define a new function to call them at once.
function changeWidthAndHeight() {
document.getElementById(this.props.image.id).height="80"
document.getElementById(this.props.image.id).width="80"
}
Then, replace the content of onMouseOver with it.
onMouseOver={changeWidthAndHeight}
Merge them into 1 function
onMouseOver={()=> {
let obj = document.getElementById(this.props.image.id);
obj.height="80";
obj.width="80";
}}
Or you can make those style a variable then update that using onMouseOver.

Categories

Resources