skip to Main Content

I want to check if a div class element has been clicked.Is there a way in Javascript. I have a conditional statement which checked whether a style has certain attributes, but there is no way I know of checking whether a div class in that conditional statement has been clicked…

Here’s my code so far:

let a = document.getElementsByClassName("roll")[0];
let b = document.getElementsByClassName("effect")[0];

a.onclick = function(){
    b.setAttribute('style','border-right:4px solid #aa2e27')
}

a.onmouseover = function(){
    if(b.hasAttribute('style','border-right:none') && a.onclick.value == "false"){
        b.setAttribute('style','border-right:4px solid #aa2e27');
    }
}

As you can see, the if condition takes place on mouseover event. Is there a way to check this? (what I entered on mouseover doesnt trigger)

2

Answers


  1. To check if a element with a specific class has been clicked, you can use an event listener on that element and update a variable when the click event occurs. Here’s an example:

    
    let divElement = document.getElementsByClassName("roll")[0];
    let isClicked = false;
    
    divElement.addEventListener("click", function() {
      isClicked = true;
      // Additional code to execute when the div is clicked
    });
    
    // You can then use the `isClicked` variable in your conditional statement
    divElement.addEventListener("mouseover", function() {
      if (b.hasAttribute("style", "border-right:none") && !isClicked) {
        b.setAttribute("style", "border-right:4px solid #aa2e27");
      }
    });
    

    In this code, we initialize the isClicked variable to false. When the element with the "roll" class is clicked, we set isClicked to true. Then, in the mouseover event listener, we check if isClicked is false before applying the desired styling.

    By using an event listener for the click event, you can capture the moment when the is clicked and update the state accordingly.

    Login or Signup to reply.
  2. You could create a variable in the outer scope to track that like this:

    let a = document.getElementsByClassName("roll")[0];
    let b = document.getElementsByClassName("effect")[0];
    let aClicked = false;
    
    a.onclick = function(){
        b.setAttribute('style','border-right:4px solid #aa2e27');
        aClicked = true;
    }
    
    a.onmouseover = function(){
        if(b.hasAttribute('style','border-right:none') && aClicked){
            b.setAttribute('style','border-right:4px solid #aa2e27');
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search