Select a different image depending on a variable - javascript

I'm trying to select a different image depending on the click.id so I have to give id to indicate the image. I'm doing it like this:
const imgChange = document.querySelector('.eyeImage img');
const eyeBtn = document.querySelectorAll('.icons .fa-eye');
eyeBtn.forEach((click) => {
click.addEventListener('click', () => {
eyeImage.classList.remove('active');
if (click.id === 'product-1') {
imgChange.src = 'images/product-1.png';
} else if (click.id === 'product-2') {
imgChange.src = 'images/product-2.png';
} else if (click.id === 'product-3') {
imgChange.src = 'images/product-3.png';
}
});
});
Is there any proper way to achieve it?

You can use expressions on a string using ` instead of ':
const imgChange = document.querySelector('.eyeImage img');
const eyeBtn = document.querySelectorAll('.icons .fa-eye');
eyeBtn.forEach((click) => {
click.addEventListener('click', () => {
eyeImage.classList.remove('active');
imgChange.src = `images/product-${click.id}.png`;
});
});
Example with a for:
for(let i = 0; i < 5; i++) console.log(`images/product-${i}`);

Related

How can i add Local Storage to my todolist?

I am doing some practice javascript exercise. My project look like 'trello' but much soft and simple.
When i writing some notes to input, javscript adding note dynamically but if i refresh the page/chrome, all things gone or lost.
So i wanna apply localstorage on my project. How can i do it.
My Note project: https://codepen.io/daniel_134/pen/NWwYKyK[My Note project]1
var input = document.querySelector('#text-input');
document.querySelector("#ad-note-btn").addEventListener("click", () => {
if (input.value.length > 1) {
// GET-INPUT-VALUE
var getvalue = input.value;
// CREATE-NEW-NOTE
const newLi = document.createElement("textarea");
newLi.value = getvalue;
newLi.className = "note-li";
// ADD-NEW-NOTE
var ul = document.querySelector('#list-items');
ul.appendChild(newLi);
// EMPTY-INPUT-WHEN-CREATING-NEW-NOTES
input.value = " ";
// DELETE-NOTES
const dleLi = document.createElement("button");
dleLi.textContent = "delete";
dleLi.className = "list-btn";
ul.appendChild(dleLi);
dleLi.addEventListener("click", () => {
newLi.remove();
dleLi.remove();
edLi.remove();
saveLi.remove();
})
// EDIT-NOTES
const edit = () => {
if( newLi.value.length > 0 ) {
newLi.disabled = true;
} else {
newLi.disabled = false;
}
}
edit()
const edLi = document.createElement("button");
edLi.textContent = "Edit";
ul.appendChild(edLi);
edLi.className = "list-btn";
edLi.addEventListener("click", () => {
if ( newLi.disabled = true ) {
newLi.disabled = false;
}else {
newLi.disabled = true;
}
})
const saveLi = document.createElement("button");
saveLi.textContent = "save";
ul.appendChild(saveLi);
saveLi.className = "list-btn";
saveLi.addEventListener("click", () => {
edit();
})
} else {
ul.appendChild();
}
})
document.querySelector("#clear-btn").addEventListener("click", () => {
input.value = " ";
})
2
it'll look like that , for example :
when you load your page .
load todoList var todoList = JSON.parse(localStorage.getItem('todo-list'))
and display it
when you add new element to your to-do list
var todoList = JSON.parse(localStorage.getItem('todo-list'));
var new_todo = [{
title:'for example ...',
complete:false
}];
localStorage.setItem('todo-list',JSON.stringify(new_todo));
}else{
todoList.push({
title:'for example ...',
complete:false
});
localStorage.setItem('todo-list',JSON.stringify(todoList));
}

Mousemove problem with classes. If i'm moving the mouse out content disappears

I have a problem with the menu. Can somebody check?
If I'm moving the mouse out content disappears.
I think there is no problem with classes.
class Menu{
constructor(id){
this.id = id;
const linkBlock = document.querySelector(`.navigation__dropdown-block-${this.id}`);
const menuLink = document.querySelector(`.navigation__link-${this.id}`);
const menuLinks = document.querySelectorAll(`.navigation__link`);
const linkBlockA = document.querySelectorAll('.navigation__dropdown-block--active')
menuLink.addEventListener('mouseenter', () => {
linkBlock.classList.add('navigation__dropdown-block--active');
menuLink.classList.add('navigation__link--active');
});
linkBlock.addEventListener('mouseenter', () => {
linkBlock.classList.add('navigation__dropdown-block--active');
menuLink.classList.add('navigation__link--active');
});
menuLink.addEventListener('mouseleave', () => {
linkBlock.classList.remove('navigation__dropdown-block--active');
menuLink.classList.remove('navigation__link--active');
});
linkBlock.addEventListener('mouseleave', () => {
linkBlock.classList.remove('navigation__dropdown-block--active');
menuLink.classList.remove('navigation__link--active');
});
}
}
const menuLinks = document.querySelectorAll('.navigation__link');
for(let i = 0; i < menuLinks.length; i++){
new Menu(i + 1);
}

Passing the Eventlistener to the correct function in JS

I have two buttons (each of them has a value which matches the id of a dish in the food menu) with two EventListeners. One button for adding something to a shopping cart and one button to remove something from the shopping cart. My problem is, that i cant figure out how to pass the Eventlistener to the correct class function. This is my code so far:
class Cart {
constructor() {
this.inhalt = [];
}
add(item) {
this.inhalt.push(item);
console.log(this.inhalt)
}
remove(item) {
for (let i = 0; i < this.inhalt.length; i++) {
if (this.inhalt[i].id === item.id) {
this.inhalt.splice(i, 1);
console.log(this.inhalt)
}
}
}
sum() {
let s = null;
this.inhalt.price.forEach(element => {
s += element
});
console.log(s)
}
}
const myCart = new Cart();
function getItem(type) {
let item = null;
for (let i=0; i<speisekarte.length; i++) {
if (speisekarte[i].id === this.value) {
item = speisekarte[i];
break;
}
}
if (type == "plus") {myCart.add(item)}
else if (type == "minus") {myCart.remove(item)};
}
let plus = document.querySelectorAll(".kaufen");
plus.forEach(el =>{
let type = "plus"; el.addEventListener("click", getItem(type));
});
let minus = document.querySelectorAll(".zurück");
minus.forEach(el =>{
let type = "minus"; el.addEventListener("click", getItem(type));
});
You shouldn't be calling the functions when registering the event listeners.
Instead of:
let plus = document.querySelectorAll(".kaufen");
plus.forEach(el =>{
let type = "plus"; el.addEventListener("click", getItem(type));
});
let minus = document.querySelectorAll(".zurück");
minus.forEach(el =>{
let type = "minus"; el.addEventListener("click", getItem(type));
});
Do this:
let plus = document.querySelectorAll(".kaufen");
plus.forEach(el =>{
el.addEventListener("click", () => getItem("plus"));
});
let minus = document.querySelectorAll(".zurück");
minus.forEach(el =>{
el.addEventListener("click", () => getItem("minus"));
});

How to check all input has value and do something

i have these inputs and i wanted to check every one of them has value then do something;
const tch_family_name = document.getElementById('tch_family_name');
const tch_lastname = document.getElementById('tch_lastname');
const tch_name = document.getElementById('tch_name');
const tch_phone = document.getElementById('tch_phone');
const first_alph = document.getElementById('first_alph');
const second_alph = document.getElementById('second_alph');
const third_alph = document.getElementById('third_alph');
const tch_bday = document.getElementById('tch_bday');
const textarea1 = document.getElementById('textarea1');
and I'm checking they have value or not like this
function checkEmpty(check) {
for (i = 0; i < check.length; i++) {
if (check[i].value == "" || check[i].value == " " || check[i].value == null) {
check[i].classList.add('inputErrorBorder')
} else {
check[i].classList.remove('inputErrorBorder')
}
}
}
//mainInfo button id
mainInfo.addEventListener('click', () => {
test = [tch_family_name, tch_lastname, tch_name, tch_phone, first_alph, second_alph, third_alph, tch_bday, textarea1]
checkEmpty(test)
})
now how to do something when all input have value;
I tried else if() but it gave an incorrect result for example when first input don't value then it wont add inputErrorBorder class to a second or third inputs.
Please help;
One of the easiest ways to add this to your current setup is to add a flag variable to the checkEmpty function and return that value. Then process the results in the EventListener
checkEmpty With hasEmpty Flag
function checkEmpty(check) {
let hasEmpty = false;
for (let i = 0; i < check.length; i++) {
if (check[i].value === "" || check[i].value === " " || check[i].value == null) {
check[i].classList.add('inputErrorBorder');
hasEmpty = true;
} else {
check[i].classList.remove('inputErrorBorder');
}
}
return hasEmpty;
}
Using hasEmpty flag from checkEmpty
mainInfo.addEventListener('click', () => {
let test = [tch_family_name, tch_lastname, tch_name, tch_phone,
first_alph, second_alph, third_alph, tch_bday, textarea1];
let hasEmpty = checkEmpty(test);
if (!hasEmpty) {
// All Have Value
} else {
// Something has missing value
}
})

Convert Select-Option to UL-LI in angular

I am migrating from js to angular and have come across a weird situation, I had designed my DOM to convert all the HTML Select tag to UL using this JS script:
var coaching = function() {}
coaching.prototype.customSelect = function(wrapper) {
wrapper.querySelectorAll('.form-ctrl').forEach(function(elm) {
if (elm.tagName == 'SELECT') {
var allOptions = elm.getElementsByTagName('option');
var allreadyCustomDropDown =
elm.parentNode.querySelector('.customDropdown');
if (allreadyCustomDropDown != null) {
allreadyCustomDropDown.remove();
}
if (allOptions.length > 0) {
var listWrapper = document.createElement('ul');
listWrapper.classList.add('customDropdown');
for (var i = 0; i < allOptions.length; i++) {
var list = document.createElement('li');
list.innerHTML = allOptions[i].innerHTML;
listWrapper.appendChild(list);
}
elm.parentNode.appendChild(listWrapper);
elm.parentNode.classList.add('customSelectWrapper');
listWrapper.querySelectorAll('li').forEach(function(liList) {
liList.addEventListener('click', function() {
liList.parentNode.parentNode.querySelector('.form-
ctrl').value = liList.innerHTML;
liList.parentNode.parentNode.classList.add('has-value');
liList.parentNode.classList.remove('visibleDropdown');
liList.parentNode.parentNode.querySelector('.form-ctrl').style.opacity = 1;
})
})
}
// listWrapper.addEventListener
}
});
wrapper.querySelectorAll('select.form-ctrl').forEach(function(elm) {
elm.addEventListener('click', function() {
document.querySelectorAll('.customDropdown').forEach(function(elm1) {
elm1.parentNode.querySelector('.customDropdown').classList.remove('visibleDropdown');
});
elm.style.opacity = 0;
elm.parentNode.querySelector('.customDropdown').classList.add('visibleDropdown');
});
});
document.addEventListener('click', (e) => {
if (!e.target.parentNode.classList.contains('customDropdown') && !e.target.parentNode.classList.contains('customSelectWrapper')) {
document.querySelectorAll('.customDropdown').forEach(function(elm) {
elm.classList.remove('visibleDropdown');
elm.parentNode.querySelector('.form-ctrl').style.opacity = 1;
});
}
});
}
var coachingInstance = new coaching();
coachingInstance.customSelect(document);
Now on HTML side I use a wrapper on the select tag
<div class="field-wrapper">
<select id="enquiryPriority" class="form-ctrl" [(ngModel)]="advancedFilterForm.priority" name="priority" formInput>
<option></option>
<option *ngFor="let priority of enqPriority" [value]="priority.data_key">
{{priority.data_value}}
</option>
</select>
<label for="enquiryPriority">Enquiry Priority</label>
</div>
My question is how can I perform this conversion on Document load in angular since typescript throws an error when I use querySelectorAll('.form-ctrl').forEach() and many other common functions that I was able to use in plain javascript.
Update ==> Tried to perform the action using a function on ngOnInit
convertSelectToUl() {
var myNodeListOne = document.querySelectorAll('.form-ctrl');
[].forEach.call(myNodeListOne, function (elm) {
if (elm.tagName == 'SELECT') {
var allOptions = elm.getElementsByTagName('option');
var allreadyCustomDropDown =
elm.parentNode.querySelector('.customDropdown');
if (allreadyCustomDropDown != null) {
allreadyCustomDropDown.remove();
}
if (allOptions.length > 0) {
var listWrapper = document.createElement('ul');
listWrapper.classList.add('customDropdown');
for (var i = 0; i < allOptions.length; i++) {
var list = document.createElement('li');
list.innerHTML = allOptions[i].innerHTML;
listWrapper.appendChild(list);
}
elm.parentNode.appendChild(listWrapper);
elm.parentNode.classList.add('customSelectWrapper');
var listNode = listWrapper.querySelectorAll('li');
[].forEach.call(listNode, function (liList) {
liList.addEventListener('click', function () {
liList.parentNode.parentNode.querySelector('.form-ctrl').value = liList.innerHTML;
liList.parentNode.parentNode.classList.add('has-value');
liList.parentNode.classList.remove('visibleDropdown');
liList.parentNode.parentNode.querySelector('.form-ctrl').style.opacity = 1;
})
})
}
}
});
var myNodeListTwo = document.querySelectorAll('select.form-ctrl');
[].forEach.call(myNodeListTwo, function (elm) {
elm.addEventListener('click', function () {
var listDropdown = document.querySelectorAll('.customDropdown');
[].forEach.call(listDropdown, function (elm1) {
elm1.parentNode.querySelector('.customDropdown').classList.remove('visibleDropdown');
});
elm.style.opacity = 0;
elm.parentNode.querySelector('.customDropdown').classList.add('visibleDropdown');
});
});
document.addEventListener('click', (e) => {
let parent = (<HTMLElement>(<HTMLElement>e.target).parentNode);
if (!parent.classList.contains('customDropdown')
&& !parent.classList.contains('customSelectWrapper')) {
var nodeDropdown = document.querySelectorAll('.customDropdown');
[].forEach.call(nodeDropdown, function (elm) {
elm.classList.remove('visibleDropdown');
elm.parentNode.querySelector('.form-ctrl').style.opacity = 1;
});
}
});
}
Just converted your JS code into TS, please try to run the same.
declare let document: any;
export class Coching {
customSelect(wrapper) {
wrapper.querySelectorAll('.form-ctrl').forEach((elm) => {
if (elm.tagName === 'SELECT') {
const allOptions = elm.getElementsByTagName('option');
const allreadyCustomDropDown =
elm.parentNode.querySelector('.customDropdown');
if (allreadyCustomDropDown != null) {
allreadyCustomDropDown.remove();
}
if (allOptions.length > 0) {
const listWrapper = document.createElement('ul');
listWrapper.classList.add('customDropdown');
for (let i = 0; i < allOptions.length; i++) {
const list = document.createElement('li');
list.innerHTML = allOptions[i].innerHTML;
listWrapper.appendChild(list);
}
elm.parentNode.appendChild(listWrapper);
elm.parentNode.classList.add('customSelectWrapper');
listWrapper.querySelectorAll('li').forEach((liList) => {
liList.addEventListener('click', () => {
liList.parentNode.parentNode.querySelector('.form-ctrl').value = liList.innerHTML;
liList.parentNode.parentNode.classList.add('has-value');
liList.parentNode.classList.remove('visibleDropdown');
liList.parentNode.parentNode.querySelector('.form-ctrl').style.opacity = 1;
})
})
}
// listWrapper.addEventListener
}
});
wrapper.querySelectorAll('select.form-ctrl').forEach((elm) => {
elm.addEventListener('click', function () {
document.querySelectorAll('.customDropdown').forEach((elm1) => {
elm1.parentNode.querySelector('.customDropdown').classList.remove('visibleDropdown');
});
elm.style.opacity = 0;
elm.parentNode.querySelector('.customDropdown').classList.add('visibleDropdown');
});
});
document.addEventListener('click', (e) => {
if (!e.target.parentNode.classList.contains('customDropdown') && !e.target.parentNode.classList.contains('customSelectWrapper')) {
document.querySelectorAll('.customDropdown').forEach((elm) => {
elm.classList.remove('visibleDropdown');
elm.parentNode.querySelector('.form-ctrl').style.opacity = 1;
});
}
});
}
}

Categories