简体   繁体   中英

on('click') function fires on second click

I have a problem, I got an li that toggles whenever an element is clicked, but the problem is that I'm trying to navigate the window to center that li when the "click" element was click. It's working but my problem is, that script only works on the second click?

My theory is that since that li is in display:none , it's not reading it on first click, rather on the second click. Is there anyway to solve this in a way that it will fire up the toggle plus the window navigation at the same time?

And also is there a way to move it dynamically(animate) in a smooth way?

Thanks guys!

SAMPLE JSFIDDLE

 $(document).on('click', "#click", function(){

  var viewportHeight = $(window).height(),
      foo = $('ul li:nth-child(2)'),
      elHeight = foo.height(),
      elOffset = foo.offset();
  $(window).scrollTop(elOffset.top + (elHeight/2) - (viewportHeight/2));
  $(foo).slideToggle();
  });

first mate try to set it visibility: hidden; not display none

if not work too, try to set timer work when you click directly, this time will be call a calculate function again ... and its will be work .. to can test it more easy .. add this to under your function ..

        $(document).on("mousemove", "#click", function(){

  var viewportHeight = $(window).height(),
      foo = $("ul li:nth-child(2)"),
      elHeight = foo.height(),
      elOffset = foo.offset();
  $(window).scrollTop(elOffset.top + (elHeight/2) - (viewportHeight/2));
  $(foo).slideToggle();
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM