0

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

Some html loads with ajax need to be displayed when the user click on another element loaded with ajax.

Example:

<!-- 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 which is set to display: none; in CSS, and I want that after a click on .block2 the CSS becomes 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 updated too).

For information:

  • The CSS are initialized 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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

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
  • 27
  • 1
  • 6
  • 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