Home > Back-end >  JavaScript - Show a div without using display:none
JavaScript - Show a div without using display:none

Time:10-11

I have a div that I want to be "activated" on a click but only the first time, only when it doesn't exist yet ; I don't want to use display:none by default because when coming back to the page afterwards I would have to click again to make it appear.

To sum up, is there any way to "activate" a div instead of using show/hide? (createElement and append would make a new one on each click...)

CodePudding user response:

You can use appendTo() for that. If you give that div an unique ID, you can check if it exists

$('button').on('click', function() {
  if( $('#uniqueID').length == 0 ) {
    $('<div id="uniqueID">This is a div</div>').appendTo('body');
  }
});
div {
  border: 1px solid blue;
  margin: 1em;
  padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add div</button>

  • Related