Matt Craig Matt Craig - 12 days ago 5x
CSS Question

Why won't the change in CSS styling caused by JavaScript remain after script finishes running?

Edit: Title makes more sense now.

I'm currently writing basic CRUD functionality using a popular web framework. In the edit section of my app, I have a 'Delete' button. When the button is clicked, I want a div containing text and two more buttons to appear, giving me the option to continue with the deletion. The delete functionality is handled by the framework, which is working just fine.

(I hate that inline CSS as much as you do, but bear with me, makes it easier for illustration purposes)


<style type='text/css'>
#overlay {
visibility: hidden; }

<form method='POST' action='', enctype='multipart/form-data'> {% csrf_token %}
<input type='submit' name='save' value='Save post'/>
<button onclick='toggleDeletion()'>Delete</button>

<div id='overlay'>
<p>Are you sure you want to delete this post? It&lsquo;ll be lost forever...</p>
<form method='POST' enctype='multipart/form-data'> {% csrf_token %}
<input type='submit' name='yes' value='Yes' />
<button onclick='toggleDeletion()'>No</button>

My JavaScript:

function toggleDeletion() {
el = document.getElementById("overlay"); = ( == 'hidden') ? 'hidden' : 'visible';

When I click the first 'Delete' button it works for about a half a second; the overlay div becomes visible. However it then vanishes, and doesn't come back. I'm relatively fresh to JavaScript, though not programming in general, and I am assuming there's some nuance of the language I'm completely missing out on. It doesn't appear to be looping through the function continuously, nor does it break. It just runs fleetingly. That or a stupid typo that's making me look like a fool.

  1. You click the button
  2. The JavaScript runs and modifies the DOM loaded into the browser
  3. The form submits (because you clicked a submit button)
  4. The browser loads a new page (which doesn't have the changes you made to the DOM with JS because they were only local)

If you don't want to submit the form when you click the button, don't use a submit button. Add type="button".