0

Im trying to change the logo in my header based on how far I've scrolled on the page. I've tried to use things such as Midnight.js, but I need to render a whole different logo on scroll, not just change the color of the picture. I've tried doing it like this, but it doesn't work.

<script>
window.onscroll = function() {myFunction()};

function myFunction() {
    if (document.body.scrollTop > 500 || document.documentElement.scrollTop > 500) {
        var source= "images/whitelogo.png";
    } else {
        var source= "images/blklogo.png";
    }
    
}
</script>
<h1 id="myP" ><a href="index.html" ><img alt="logo" src=source; style="height:2.8em" /></a></h1>

Thanks for your help!!!

Disha Rao
  • 35
  • 4

3 Answers3

0

There are several errors in your code. You can't use JavaScript variables outside of the script tag.

This code should work however:

<script>
window.onscroll = function() {myFunction()};

function myFunction() {
    if (document.body.scrollTop > 500 || document.documentElement.scrollTop > 500) {
        document.getElementById("logo").src = "images/whitelogo.png";
    } else {
        document.getElementById("logo").src = "images/blklogo.png";
    }
    
}
</script>
<h1 id="myP" ><a href="index.html" ><img alt="logo" id="logo" src=""; style="height:2.8em" /></a></h1>
Sub 6 Resources
  • 1,674
  • 15
  • 31
0

You can use jquery .scrollTop() function to get the current location. Take a look on the question below

How can I determine the direction of a jQuery scroll event?

So now all you need to do is resize your logo :)

Community
  • 1
  • 1
0

You added jQuery within your question tags but I don't see you using it here (which is ok). If you would like to try with jQuery then you can use something similar to this:

$(window).scroll(function() {
  if ($(this).scrollTop()>500) {
      $('#myP img').attr('src', 'images/whitelogo.png');
  } else {
      $('#myP img').attr('src', 'images/blklogo.png');
  }
});

And change your HTML like this:

<h1 id="myP"><a href="index.html"><img alt="logo" src='images/blklogo.png' style="height:2.8em" /></a></h1>

My preference however is to use this type of images as an element background defined in CSS rules. You could create a CSS rule like:

#myP a {
   display: block;
   height: Npx;
   width: Mpx;
   background-image: ('images/blklogo.png');
   ...
}

I think this will help you keep things organized and maintainable.

zJorge
  • 798
  • 2
  • 13
  • 26