Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move to DIV when toggled with jQuery

I have been reading around, and I am trying to have the screen move to the div that is being toggled. It is at the bottom of my site so when you toggle the contact form, you can't tell it is there unless you scroll down.

I have this snippet of jQuery that doesn't seem to be working

//contact toggle
$("#show-con").click(function(){
  $("#contact-wrap").slideToggle("slow");
  $("#contact-wrap").animate({scrollTop: $("#contact-wrap").offset().top});
});

The toggle works fine, but it will not scroll to the div.

I read some older articles on here, but unfortunately they linked out to sites no longer active.

like image 205
souporserious Avatar asked Jun 29 '12 20:06

souporserious


2 Answers

This will work, use html, body for your selector:

$("#show-con").click(function(){
  $("#contact-wrap").slideToggle("slow");

  if ($("#contact-wrap").is(':visible')) {
     $("html, body").animate({scrollTop: $("#contact-wrap").offset().top});
  }
});

Also added check if element is visible only then scroll not otherwise.

like image 91
Blaster Avatar answered Oct 27 '22 18:10

Blaster


To define this for all divs that have a toggle on them, please refer to http://jsfiddle.net/LkTf8/79/.

$(document).ready(function() {
  $(".trigger").click(function(e){
  var $toggled = $(this).attr('id');
  var $paneltoggled = $(this).next(".panel").attr('id');

  $(this).next(".panel").slideToggle('slow'); 
  if ($("#" + $paneltoggled).is(':visible')) {
    $("html, body").animate({scrollTop: $("#" + $paneltoggled).offset().top});}    
  });
});
like image 40
padma2129 Avatar answered Oct 27 '22 18:10

padma2129