Search code examples
javascriptinternet-explorerfirefoxonscroll

onscroll only fires once


I have a javascript file I am using to align a single absolute div to always be inline with the horizontal scroll position.

I can't figure out what's not working with my code - onscroll seems to fire once and then never fire again in both internet explorer and firefox.

Anyone have any ideas? I've been looking this up for a bit and I can't figured out the error. (I have tried both onscroll += and onscroll =, neither work). That 39 offset is just to make sure the script fired until I get it to work.

window.onload=scrollSet;

function scrollSet(){
	window.onscroll += KeepLeftAtScroll();
}


function KeepLeftAtScroll(){
	var ele=document.getElementById("topAboveMenuMargin");
	if (ele != null){
		ele.style.left = 39+ document.documentElement.scrollLeft;
	}
		
}


Solution

  • Fixed the issue. Apparently javascript does not like seperating assignement and declaration, as

    window.onscroll = function KeepLeftAtScroll(){
    	var ele=document.getElementById("topAboveMenuMargin");
    	if (ele != null)
    	{
    		ele.style.left = window.pageXOffset;
    	}
    }

    works and does what I want it to. It didn't seem to like "window.onscroll = KLAS()" but was ok with "window.onscroll = function KLAS(){}". I originally did the onload portion since I wasn't originally checking for null on my element and did it that way to get around that issue.

    Either way, it seems solved. Thanks for all the help all.