javascripthtmlbuttononclickevent-listener

Using two buttons with onclick events that continuously change each other?


This is what I'm trying to accomplish:

Two buttons (left and right). The left button starts off with a cursor of "not-allowed" on hover (indicating starting off the left button should not be clicked). When the right button is clicked, this turns the right button's cursor to "not-allowed" on hover indicating it shouldn't be clicked after being clicked once, while simultaneously making the left button's cursor "arrow" on hover indicating the left button is now open to be clicked after the right button is clicked.

I have written some code using javascript and using "onclick events". This code is not what I want, but gives you a visual of what I'm trying to accomplish as I explained above:

function prev() {
  document.getElementById("slide-arrow-prev").style.cursor = "not-allowed";
  document.getElementById("slide-arrow-next").style.cursor = "arrow";
}

function next() {
  document.getElementById("slide-arrow-next").style.cursor = "now-allowed";
}
<body>
  <button id="slide-arrow-prev" onclick="prev()"> < </button>
  <button id="slide-arrow-next" onclick="next()"> > </button>
</body>

Basically, the idea is an image carousel that slides when the left and right buttons are pushed. I'm trying to mimic the carousel used on the homepage of aliexpress (you can look there for reference). Once the carousel reaches it's slide limit, the cursor of the left/right buttons are "not-allowed" indicating they can't slide anymore images.

I tried using an event listener but not really sure if I was supposed to, so I took that out.

How can I write this please using html, javascript and/or CSS?


Solution

  • You can toggle a .not-allowed class on and off, in order to change the cursor for each button.

    function handleClick(e) {
    
      ['slide-arrow-prev', 'slide-arrow-next'].forEach(id => 
        document.getElementById(id).classList.toggle('not-allowed'))
    
      console.log(`${e.currentTarget.id} clicked`)
    
    }
    button {
      cursor: arrow;
    }
    
    .not-allowed {
      cursor: not-allowed;
    }
    <button id="slide-arrow-prev" onclick="handleClick(event)" class="not-allowed"> &lt; </button>
    <button id="slide-arrow-next" onclick="handleClick(event)"> &gt; </button>