Search code examples
javascriptjqueryfadeinfadefadeout

Map Informations with fadeIn and fadeOut


I have a map with some pinpoints that, if you click on them show some information. The plan was, that I can click a Icon and it shows a div, if I now click the same icon the div will disapear.

As long as i got show() it works but if I put in fadeIn() it reapears on the second click.

Here my script so far

<script type="text/javascript">
    jQuery(document).ready(function() {
        $(".icon-location").on('click', function(event){
          $('[id^="ort-box-"]').fadeOut('slow');
        });


        var mouseX;
        var mouseY;
        $(document).ready(function(e) {
           mouseX = e.pageX;
           mouseY = e.pageY;
        });

        $(".icon-location").on('click', function(event){
            var currentId = $(this).attr('id');
            $("#ort-box-"+currentId).show().css({position:"absolute", top:event.pageY, left: event.pageX, "z-index":"998"});
        });
    });
</script>

EDIT:

Thanks to Max I got something startet but there is some logic mistake I must have made.

$(".icon-location").on('click', function(event){
            $('[id^="ort-box-"]').fadeOut('slow');

        if(!$(this).hasClass('ortActive')){

                    var currentId = $(this).attr('id');
                    $("#ort-box-"+currentId).fadeIn('slow').css({position:"absolute", top:event.pageY, left: event.pageX, "z-index":"998"});        

            $(this).addClass('ortActive');
        }else {
            $(this).removeClass('ortActive');
        }
    });

Solution

  • You're attaching 2 eventhandlers on the same DOM element. So if you click on it, both handlers will fire the event and both functions will be called.

    Maybe use something like

    $(this).addClass('active');
    

    if you trigger the event for the first time, check when you press again with

    if($(this).hasClass('active')){ ... 
    
      $(this).removeClass('active');
    }
    

    This way you can be sure, that you can trigger only the wanted parts of the event handlers.