Okay so basically I'm using a button type in HTML, I have two buttons with different id's as an example:
<button id='Sucky27' ></button>
<button id='Sucky28' ></button>
the buttons call a javascript function as follows:
document.getElementById("Sucky28").addEventListener("click", function() {
document.querySelector(".BuildingMenu").style.display = "flex";
})
when the button is pressed it opens a building menu then when you click on an item in the menu ie a house this gets runned
document.getElementById("House").addEventListener("click", function() {
document.querySelector("function.caller.id").style.backgroundImage = "url(./download.PNG)";
})
I'm wondering if there's a way for the querySelector to find the id of the caller which initiated the building menu so if id sucky27 opens the menu it uses its id and changes the its properties
I hope I explained it well enough for you to understand
CodePudding user response:
The event handler has context to the element it is attached to via this
.
const exampleBtn = document.getElementById("example");
let clicked = false;
exampleBtn.addEventListener("click", function(evt) {
this.style.backgroundColor = clicked ? "green" : "red";
clicked = !clicked;
});
<button id="example">Click</button>
CodePudding user response:
If you want multiple buttons with the same functionality, you should use a class, use getElementsByClassName to find them, then loop over each and then assign the state to dataset on the element.
[].forEach.call(document.getElementsByClassName('btn-coloured'), function (el) {
el.addEventListener("click", function(evt) {
this.style.backgroundColor = this.dataset.clicked ? "green" : "red";
this.dataset.clicked = !this.dataset.clicked;
})
});
<button >Click</button>
<button >Click</button>
<button >Click</button>
Else you will end up repeating code for button 2
CodePudding user response:
I don´t know if it helps to you, but I used to use long time ago the localStorage and sessionStorage to save this kind of things for using it later.
Example:
document.getElementById("Sucky28").addEventListener("click", function() {
sessionStorage.setItem('triggeredBtnId', 'Sucky28');
document.querySelector(".BuildingMenu").style.display = "flex";
})
and then:
document.getElementById("House").addEventListener("click", function() {
const triggeredBtnId = sessionStorage.getItem('triggeredBtnId');
document.querySelector(triggeredBtnId).style.backgroundImage = "url(./download.PNG)";
})
this sessionStorage variable will be deleted automatically when the browser or tab is closed.