This jQuery code snippet keeps an element in view as the page scrolls. A demo shows this effect on a right sidebar ad. The code is presented both as a standalone script and as a reusable jQuery plugin. Finally, a FAQ section addresses common jQuery scrolling questions.
The Code (Standalone):
//keep element in view (function($) { $(document).ready(function() { var elementPosTop = $('#jq4u-sidebar-ads').position().top; $(window).scroll(function() { var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height(); if (wintop > elementPosTop) { $('#jq4u-sidebar-ads').css({ "position": "fixed", "top": "10px" }); } else { $('#jq4u-sidebar-ads').css({ "position": "inherit" }); } }); }); })(jQuery);
The Code (jQuery Plugin):
/** * jQuery keep element in view plugin. * * @author Sam Deering * @copyright Copyright (c) 2012 jQuery4u * @license http://jquery4u.com/license/ * @link http://jquery4u.com * @since Version 1.0 * @notes Plugin only works on scroll down elements. */ (function($) { $.fn.keepElementInView = function() { var elemPosTop = this.position().top; $(window).scroll(function() { var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height(); if (wintop > elemPosTop) { this.css({ "position": "fixed", "top": "10px" }); } else { this.css({ "position": "inherit" }); } }); return this; }; $(document).ready(function() { $('#jq4u-sidebar-ads').keepElementInView(); }); })(jQuery);
Frequently Asked Questions (FAQs):
This section provides concise answers to common questions about jQuery element view scrolling, including techniques for animated and instant scrolling, horizontal scrolling, viewport checks, and button-triggered scrolling. The code examples are slightly reformatted for improved readability.
Q1: Animate scroll to element?
$('html, body').animate({ scrollTop: $("#elementID").offset().top }, 2000);
Q2: Instant scroll to element?
$('html, body').scrollTop($("#elementID").offset().top);
Q3: Horizontal scroll to element?
$('html, body').animate({ scrollLeft: $("#elementID").offset().left }, 2000);
Q4: Check if element is in viewport?
function isInViewport(element) { let elementTop = $(element).offset().top; let elementBottom = elementTop + $(element).outerHeight(); let viewportTop = $(window).scrollTop(); let viewportBottom = viewportTop + $(window).height(); return elementBottom > viewportTop && elementTop < viewportBottom; }
Q5: Scroll to element on button click?
$("#buttonID").click(function() { $('html, body').animate({ scrollTop: $("#elementID").offset().top }, 2000); });
The above is the detailed content of jQuery Keep Element in View When Scrolling. For more information, please follow other related articles on the PHP Chinese website!