0

I'm loading element on a page with ajax and JQuery for a personnal project. But it's impossible to display some element in a very specific situation after they're append to the DOM .

Some html load with ajax need to be display when the user click on another element load with ajax.

Exemple :

<!-- Element load with ajax and append to DOM -->

<div class="block1">
    <p>You have clicked</p>
</div>
<div class="block2">
    <p>Some Text</p>
</div>

I have .block1 wich is set to display: none; in css, and I want that after a click on .block2 the css become display: flex for .block1.

So I have made this function with JQuery :

$(".block2").click(function () {

    if ($(".block1").css("display") === "none") {
        $(".block1").css("display", "flex");
    } else {
       $(".block1").css("display", "none");
    }

});

My trouble is that :

  • The function work fine when .block1is set to display: flex by default (one click on .block2 makes disappear .block1, the next click makes appear .block1).

  • This doesn't work when .block1 is set by default on display: none. But the function is correctly detect (I had set some console.log() message, and the css are update too).

For information :

  • The css are initialised in a stylesheet.

So my question is :

Why this isn't working when the css is by default display: none;, and work perfectly when the css is by default display: flex;. And how I can fix that ?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126

1 Answers1

1

replace $(".block2").click b

$(document).on('click', '.block2', function(){

     if ($(".block1").css("display") === "none") {
        $(".block1").css("display", "flex");
     } else {
         $(".block1").css("display", "none");
    }

  }
)
Issa Dicko
  • 31
  • 1
  • 5
  • Could you please explain why ? This is not obvious to me, and perhaps to other users... https://stackoverflow.com/q/9122078/1207019 – bdulac Aug 27 '19 at 10:13
  • 1
    I myself had this problem. it is due to the fact that when we use click this only for the elements already present in the DOM at the time of the loading of the page. But if we add other elements by ajax or javascript simply they are not supported. But with $ (container) .on ('click', 'selector', handler) all current or future elements are supported. Thank you !!! – Issa Dicko Aug 27 '19 at 10:29