Hello, everyone i try to hide and show description, so i created a function to do it. and it works perfectly but if i attend to hide and show another description, i must do another function, how can i create ONLY one function to do the something without doing two functions that does the same. I have link so you guys can have a better understanding what im doing. This only works for multiple functions. but i tryed to do one main function to do the same but Im having trouble, the function is commented.
thanks.
https://codepen.io/ivanmt07/pen/oNveGoj?editors=1011
You’re problem is that you’re using the same id twice in the same html page. You can add an onClick to the html or use a different identifier such as class or name (or use a different tag such as button) and then use querySelectorAll or getElementsByClassName and loop through them to add the event listeners. Something like :
const buttons = document.getElementsByClassName('actionButton');
Array.from(buttons).forEach(button=>{
button.addEventListener('click',doTheThing);
});
function doTheThing(e) {
...//do the thing
}
but something like this might work for you:
<button onClick="doTheThing(this)">hit me</button>
<script>
function doTheThing(e) {
//...
}
</script>
Your code does work when there is only one element with the id of showbtn.
Hello @JanShah thank you for your reply, i did actually trying to work on your code, but for some reason i did not get it working, so i try do figured out by my own and i actually came up with a great solutions so here is the code and the link for the working demo. Althought thanks for your help it did help a lot and also to clear some doughts that i have
// hide and show job sections
var showbtn = document.getElementsByClassName('showbtn');
for( var i = 0; i < showbtn.length; i++ ){
showbtn[i].addEventListener('click', function(){
var panel = this.nextElementSibling;
if( panel.style.display === 'block' ){
panel.style.display = 'none';
}else{
panel.style.display = 'block';
}
});
};
with this code it work i used the nextElementSibling so it worked ok!.
https://codepen.io/ivanmt07/pen/oNveGoj?editors=1111