0

I'm using the follow code to make the display appear:

<div id="create_phase{{ forloop.counter }}" class="w3-modal" onclick="this.style.display='visible'">

and the follow code to hidden display:

<a onclick="document.getElementById('create_phase{{ forloop.counter }}').style.visibility = 'hidden'">X</a>

It works fine, but i can't make display appear again after hidden it.

Any suggestions?

searcher__dm01
  • 109
  • 1
  • 8
  • Why is your ID "create_phase{{ forloop.counter }}"? IDs cannot have spaces ([or at least are not supposed to](https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html)) – Libra Nov 15 '21 at 01:32
  • It's a Django project, so i'm using MTV pattern project... – searcher__dm01 Nov 15 '21 at 01:33
  • I don't know much about that (and you didn't tag it) but I'm not entirely sure that's normal, I think your `div` is being given three IDs: `create_phase{{`, `forloop.counter`, and `}}`, so when you try to find it via getElementById there is technically no element with that ID – Libra Nov 15 '21 at 01:36
  • 1
    If you hide the div with `.style.visibility = 'hidden'`, then you need to show it with `.style.visibility = 'visible'`, not `this.style.display='visible'`. – Rickard Elimää Nov 15 '21 at 01:39
  • @RickardElimää, in this way the display is not closing anymore... Idk why – searcher__dm01 Nov 15 '21 at 01:48

2 Answers2

0

Like Laif said in the comments, spaces in your IDs are not a good idea. I think the best solution is to use IDs with proper naming conventions that the DOM plays well with.

But a possible (hacky) solution could be prefacing the spaces in your getElementById call with \ to properly escape them.

Here's a CodePen: https://codepen.io/milofultz/pen/KKvGJbJ

Milo Fultz
  • 17
  • 1
  • 5
0

You need to give your IDs proper names (cannot have spaces), as it is now, your div actually has 3 separate IDs.

and you need to change .style.visibility = 'visible', to .style.visibility = 'hidden' as your original code is not modifying the same style.

<div id="ele1" class="w3-modal" onclick="this.style.visibility='hidden'">
  test
</div>
  <a onclick="document.getElementById('ele1').style.visibility = 'visible'">X</a>

Notice, in this snippet I had to reverse the way you were trying to hide and show content in the original, because a hidden element is not clickable, if you want to be able to click it. I would use opacity instead, like this:

<div id="ele1" class="w3-modal" onclick="this.style.opacity=100">
  test
</div>
  <a onclick="document.getElementById('ele1').style.opacity=0">X</a>
Libra
  • 2,544
  • 1
  • 8
  • 24