Search code examples
javascriptjqueryhtmlcssmousehover

JQuery - Darken contents of any element i hover over containing a certain class


I want to create a hover over event that darkens any element with the class "hover-change".

I don't want to simply change the background color of the triggered element because I want to darken everything (icons, text, background). A solution I have seen online is to overlay another div on top of the selected that is grey/transparent, and when you hover over/out the element, this overlay becomes visible/invisible.

This solution wont work because I dynamically create divs, and I want to attach this functionality to many different elements.

A high level example of what I expect would be nice solution would be:

 $(".hover-change").on("mouseover",function(e) {
   $(e.target).css(  /*make entire element darker*/ );

 });

 $(".hover-change").on("mouseout",function(e) {
    $(e.target).css(  /*make entire element normal colour*/ );
 });

I can't overlay a "hidden dark transparent pane" over EVERY element because I am dynamically creating the html with handlebars.

Thanks heaps to anyone that can help me out! :)


Solution

  • I can't overlay a "hidden dark transparent pane" over EVERY element because I am dynamically creating the html with handlebars.

    Actually you can, just do it, dynamically.

    for example:

    $('.item').on("mouseover", function(){
      $(this).append('<div class="overlay"></div>')
    })
    $('.item').on("mouseout", function(){
      $('.overlay', this).remove();
    })
    .item {
      display: inline-block;
      position:relative;
      border: 1px solid rgba(0,0,0,.125);
      background-color: rgba(253,253,253,1);
      margin: 2px;
      width: 40px;
      height: 40px;
      text-align:center;
    }
    .overlay {
      position: absolute;
      top: 0;
      left: 0;
      pointer-events: none;
      background-color: rgba(0,0,0,.75);
      width: 100%;
      height: 100%;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="item">
      text
    </div>
    <div class="item">
      text
    </div>
    <div class="item">
      text
    </div>
    <div class="item">
      text
    </div>