addEventListener() and function parameters in JS

Hi,
I’m working on a small project, but I got stuck.
I want to change classes in my div’s in HTML with JS when I click on buttons, without using the function onclick(), but addEventListener() instead. I have already made it work, but for every DIV I want to change I had a seperate function.

  1. document.getElementById(“liExample”).addEventListener(“click”, load, true);
  2. function load()
  3. {
  4. var element1 = document.getElementsByClassName("show-class")[0];
    
  5. element1.classList.remove("show-class");
    
  6. element1.classList.add("hidden-class");
    
  7. var element2 = document.getElementById("EXAMPLE");
    
  8. element2.classList.remove("hidden-class");
    
  9. element2.classList.add("show-class");
    
  10. }

…and for every other DIV, I have a separate function.

How do I put a parameter in my first line of code that will be used in my function and will change my EXAMPLE in 7’th line?

what are you trying to show and hide?
Once the element divs are hidden how you can click back on that div?

When a page loads there is already one DIV that is shown and when I click on the button I want to hide current DIV and load new one, so first 3 lines of function are hidding current DIV and 3 next should load new one.

I don’t want to get into details with your code requirement but try this, it will help you to resolve the problem.

<div id="main">
    <div id="example1"></div>
    <div id="example2"></div>
  </div>
document.getElementById('main').addEventListener("click", function(e){
  e.preventDefault();
  var elem = e.target.id;
  document.getElementById(elem).classList.add('Show');
  console.log(elem)
})
1 Like