Paul Paul - 1 month ago 9
CSS Question

Getting a div to appear with onclick addClass

I am attempting to do an onclick event where the show class is added, however, I cannot get my

new-goal-container
to appear when 'Create new goal' is clicked.

I do not want this to be a toggle, simply an add class. As my code shows, I am trying to get this to do a quick fadeIn appearance with css. Is there a better approach to this, because now even though nothing is showing the div is still taking up space, which when the container is not visible, I want it to seem as if it doesn't exist.



$("#new-goal-button").click(function() {
$("#new-goal-container").addClass("show");
});

#new-goal-container {
-webkit-opacity: 0;
opacity: 0;
margin-top: 30px;
border: 1px solid black;
height: 500px;
width: 400px;
padding: 10px;
}
.show {
-webkit-opacity: 1;
opacity: 1;
-webkit-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="new-goal-button">Create new goal</div>
<div id="new-goal-container">
<input type="text" placeholder="Goal Title">
<textarea placeholder="Goal Description">
</div>




Answer

The issue is due to an id selector being more specific than a class selector. Therefore, opacity: 0 overrides opacity: 1. Add the id and class selector together to give them a higher specificity than the original id selector alone.

Also note that your textarea element needs a closing tag, the transition rule should ideally be on the base rule of the element and only apply to the opacity rule and finally the -webkit- vendor prefix is no longer required.

$("#new-goal-button").click(function() {
  $("#new-goal-container").addClass("show");
});
#new-goal-container {
  opacity: 0;
  margin-top: 30px;
  border: 1px solid black;
  height: 500px;
  width: 400px;
  padding: 10px;
  transition: opacity 1s ease-in-out;
}
#new-goal-container.show {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="new-goal-button">Create new goal</div>
<div id="new-goal-container">
  <input type="text" placeholder="Goal Title">
  <textarea placeholder="Goal Description"></textarea>
</div>

Here's a working example in a jsFiddle too as SO Snippets seem to be broken at the moment:

Working example