Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I hide an element when the page is scrolled?

Ok, I'm a little stumped.

I'm trying to think the angular way coming from a jQuery background.

The problem: I'd just like to hide a fixed element if the window is not scrolled. If someone scrolls down the page I would like to hide the element.

I've tried creating a custom directive but I couldnt get it to work as the scroll events were not firing. I'm thinking a simple controller like below, but it doesnt even run.

Controller:

.controller('MyCtrl2', function($scope,appLoading, $location, $anchorScroll, $window ) {    angular.element($window).bind("scroll", function(e) {        console.log('scroll')        console.log(e.pageYOffset)        $scope.visible = false;    }) }) 

VIEW

<a ng-click="gotoTop()" class="scrollTop" ng-show="{{visible}}">TOP</a> 

LIVE PREVIEW http://www.thewinetradition.com.au/new/#/portfolio

Any ideas would be greatly appreciated.

like image 457
MichaelBell Avatar asked Nov 27 '13 21:11

MichaelBell


People also ask

How do you hide an element in web page?

CSS Display Property. Each element has a default display value like inline-block , block , table ..etc. To hide an element with the display property, we should use display: none . When an element is hidden with display: none , all of its descendants will be removed along with it.

How do you hide an element?

You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.

How do you hide and show elements?

Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”. document. getElementById("element").

How do you know if an element is visible in the screen during scrolling?

To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0. The Javascript code could be written as : window.


1 Answers

A basic directive would look like this. One key point is you'll need to call scope.$apply() since scroll will run outside of the normal digest cycle.

app = angular.module('myApp', []); app.directive("scroll", function ($window) {     return function(scope, element, attrs) {         angular.element($window).bind("scroll", function() {             scope.visible = false;             scope.$apply();         });     }; }); 

I found this jsfiddle which demonstrates it nicely http://jsfiddle.net/88TzF/

like image 65
eddiec Avatar answered Oct 02 '22 16:10

eddiec