jQuery addClass example

Change class name on click in jQuery

by mark edwards

HTML

<button id='coverIt' >Cover It</button>
<button id='uncoverIt'>Uncover It</button>
<div id='mainDiv'>primary div</div>
<div  id='overlay'><p>covered!!</p></div>

CSS

#mainDiv {
     width: 250px;
     height: 200px;
     border: 2px solid;
     margin-left: 400px;
     margin-top: 150px;
}

#overlay {
  background-color: red;
  margin: auto;
  
  position: absolute;
  left: -5000px;
  opacity: 0.7;
}
#overlay p {
margin: 0;
    background: yellow;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%)
    }

JavaScript

// handle click and add class
$('#coverIt').on("click", () => {
    coverDiv('div#mainDiv');
})

function coverDiv(divName) {
 $("div#overlay")
      .css({
         'top': $(divName).offset().top,
         'left': $(divName).offset().left,
         'width': $(divName).width(),
         'height': $(divName).height()
      })
}

$('#uncoverIt').on("click", () =>{
   $("#overlay")
      .css({
         'left': '-5000px',
      })
})