javascript - Jquery Multiple togglefade -


i'm using following code create pop boxes

$(document).ready(function() {    $('.item-link').click(function(e){      e.preventdefault();      var id = $(this).attr('id');      $('#pop-up-' + id).fadetoggle();    });  });
.pop-up{    display:none;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <a href="#" id="1" class="item-link">  link 1  </a>  <a href="#" id="2" class="item-link">  link 2  </a>  <a href="#" id="3" class="item-link">  link 3  </a>  <a href="#" id="4" class="item-link">  link 4  </a>    <div class="pop-up" id="pop-up-1">  content 1  </div>  <div class="pop-up" id="pop-up-2">  content 2  </div>  <div class="pop-up" id="pop-up-3">  content 3  </div>  <div class="pop-up" id="pop-up-4">  content 4  </div>

it works fine, closed pop when link click or click anywhere else on page. i'm not great jquery

to able close pop ups when user clicks anywhere on page, need capture click event @ higher level links relies on events "bubbling" original target document or window. way, can react clicks occur anywhere in document.


additionally, don't use <a> elements when aren't navigating anywhere. element can given click event handler, use best elements content. added benefit don't have cancel (with e.preventdefault()) native behavior of clicking on, span a because there no native click behavior of span.

lastly, best-practice, should not give elements id values start number.

from mdn:

note: using characters except ascii letters, digits, '_', '-' , '.' may cause compatibility problems, weren't allowed in html 4. though restriction has been lifted in html 5, id should start letter compatibility.

see comments inline below:

$(document).ready(function() {      // catch clicks, no matter originated    $(document).on("click", function(e){            $(".pop-up").hide("slow");  // hide pop ups          // show 1 requested. event target (e.target here)      // represents actual object event originated from.      $("#pop-up-" + e.target.id).show("slow");        });    });
/* make span elements look/feel links: */  .item-link {    cursor:pointer;    text-decoration:underline;    color:blue;  }    .pop-up{    display:none;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <span id="a" class="item-link">link 1</span> |  <span id="b" class="item-link">link 2</span> |  <span id="c" class="item-link">link 3</span> |  <span id="d" class="item-link">link 4</span>    <div class="pop-up" id="pop-up-a">content 1</div>  <div class="pop-up" id="pop-up-b">content 2</div>  <div class="pop-up" id="pop-up-c">content 3</div>  <div class="pop-up" id="pop-up-d">content 4</div>


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -