Search code examples
jqueryfadeinvisible

fadeIn element on click and then show another element


I would like to fadeIn an element A on click and then show another element B because element A is visible. Unfortunately my code does not work, can anybody help me?

https://jsfiddle.net/jxma8zfu/17/

$("#toggle").on("click", function () {
    $("#hallo").fadeIn();
});
$("#toggle").on("click", function () {
    $("#hallo").fadeOut();
});



$(function() {
    if($("#hallo").is(":visible")) {
        $("#cursor").fadeIn(1000); 
    }
});

Solution

  • You can use only one event handler for toggle div and check its visible or not depending this hide/show your other elements .

    Demo Code :

    $("#toggle").on("click", function() {
      //check if hallo is visible means we need to hide..(toggle) 
      if ($("#hallo").is(":visible")) {
        $("#hallo").fadeOut();
        $("#cursor").fadeOut(1000);
      } else {
        //show...
        $("#hallo").fadeIn();
        $("#cursor").fadeIn(3000);
      }
    });
    #toggle {
      position: fixed;
      top: 20px;
      left: 20px;
    }
    
    #hallo {
      display: none;
      position: absolute;
      top: 80px;
      left: 20px;
      width: 200px;
    }
    
    #cursor {
      display: none;
      position: fixed;
      top: 150px;
      left: 150px;
      background: yellow;
      pointer-events: none;
      mix-blend-mode: difference;
      z-index: 999999 !important;
      font-size: 2.0em;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p id="toggle">
      toggle
    </p>
    
    <p id="hallo">
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
    </p>
    
    <div id="cursor">
      Lorem ipsum
    </div>