skip to Main Content

I have a button where it’s background changes when you hover, as well as when you click it. To make it so it changes when you click, I made it to where you use the mousedown event. This seems to override the mouseenter and mouseleave events. When the mousedown event happens, it seems to disable the CSS hover events. I have already tried to add mouseenter and mouseleave, and it hasn’t worked.

            let button = document.querySelector(".shoot");

            button.addEventListener("mousedown",()=>{
                // REMEMBER TO FIX HOVER EFFECTS
                button.style.backgroundColor = "dodgerblue";           
            })

            
            button.addEventListener("mouseup",()=>{
                button.style.backgroundColor = "#d3d3d3";
            })
.shoot {
    width:200px;
    padding-top:20px;
    height:40px;
    font-size:18px;
    background-color:#d3d3d3;
    border-radius:30px;
    font-family:Semi-Casual;
    color:white;
    text-align:center;
    margin:auto;
}
.shoot:hover {
    background-color:#c3c3c3;
    cursor:pointer;
}
<div class="shoot">
    Shoot
</div>

2

Answers


  1. Use event mouseover / mouseout. Also don’t force mouseup on the element as it won’t do what you want because if i drag the mouse out the thing is still there

    Login or Signup to reply.
  2. Inline styles will take precedence over the CSS rules defined in a stylesheet, so that’s why the hover effect is not working as expected.

    So, instead of using Javascript to set the backgroundColor directly, use javascript to add a css class to the element, which ultimately uses CSS (also) to set the background-color.

    let button = document.querySelector(".shoot");
    
    button.addEventListener("mousedown", () => {
        button.classList.add("active");
    });
    
    button.addEventListener("mouseup", () => {
        button.classList.remove("active");
    });
    
    button.addEventListener("mouseleave", () => {
        button.classList.remove("active"); // this ensures the button returns to its normal state even if the mouse is still down
    });
    .shoot {
        width:200px;
        padding-top:20px;
        height:40px;
        font-size:18px;
        background-color:#d3d3d3;
        border-radius:30px;
        font-family:Semi-Casual;
        color:white;
        text-align:center;
        margin:auto;
    }
    
    .shoot:hover {
        background-color:#c3c3c3;
        cursor:pointer;
    }
    
    .shoot.active {
        background-color: dodgerblue;
    }
    <div class="shoot">
        Shoot
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search