Link to home
Start Free TrialLog in
Avatar of catonthecouchproductions
catonthecouchproductionsFlag for United States of America

asked on

When element hits top of page - have at top

I have been trying to work with this code:

$(window).scroll(function() {
	var nav_ele = $('nav');
	var nav_coord = $('nav').offset();
	console.log($('header').scrollTop());
	
	if(nav_ele==nav_coord.top){
		$('nav').css('position','absolute');
	}
	
    $('nav').css('top', $(this).scrollTop() + "px");
});

Open in new window


I have this page -- goo.gl/kR946 -- the nav element with the discover and engage headlines will stay at the top when hits the top of the page (top:0)

I am thinking this.

1. Use window.scroll as as listener
2. Check via conditional - if the nav element hits the top, then switch the positioning to absolute and add z-index and all other properties
3. Then set the scrollTop to the top of the page.
4. When you scroll back it will RESET and be as if you came back on the page via refresh.

Any ideas?

Thanks,

Ryan
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Assuming you are using jQuery, you need to add some # $('#nav')

Avatar of catonthecouchproductions

ASKER

Im using HTML5, so no need to add #.
But this is jQuery right? So you assign nav_ele to the jQury object and then later compares it to an attribute or property. That also does not look right
Yeah it is. I should have clarified about that conditional. I dont think that is the right way to do it and yes I see what you're saying.

I was trying to do:

when my element hits the top of the page switch to: absolute and top:0 to keep it at the top of the page, then when you scroll back return it to its original CSS properties (no absolute, etc)

Thanks,

Ryan
Yes I do. Interesting. I'll have a look but hope others will chime in
Ok, thank you!
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Perfect solution!