Search code examples
javascripthighlightmouseover

Javascript: Highlight all paragraphs when the mouse moves over them and then revert back once the mouse has passed


I am completely new to Javascript; please could someone assist me with my question in the simplest way possible for me to understand.


Solution

  • You can do this with CSS or Javascript. Either way, the result is the same.

    CSS

    You can do this by wrapping the paragraphs in a <div>, and then making a CSS :hover selector.

    .paragraphs:hover {
      color: lightgreen;
    }
    <div class="paragraphs">
      <p>One</p>
      <p>Two</p>
      <p>Three</p>
    </div>

    JS

    Wrap all the paragraphs in a <div>, then add an mouseenter and mouseleave event listener.

    var paragraphs = document.querySelector('.paragraphs');
    
    paragraphs.addEventListener('mouseenter', e => {
      paragraphs.style.color = 'lightgreen';
    });
    
    paragraphs.addEventListener('mouseleave', e => {
      paragraphs.style.color = 'black';
    });
    <div class="paragraphs">
      <p>One</p>
      <p>Two</p>
      <p>Three</p>
    </div>