Guide to dynamically altering the header logo as you scroll further

I'm attempting to dynamically change the logo in my header based on how far I've scrolled down the page. While I have experimented with libraries like Midnight.js, I specifically need to display an entirely different logo when scrolling, not just alter the image's color. Although I tried implementing a solution like the one below, it doesn't seem to be working as intended.

<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>

Any assistance provided will be greatly appreciated!

Answer №1

There seems to be a few mistakes in the code you provided. Remember that JavaScript variables should only be used within the script tags.

Here is an improved version of your code:

<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>

Answer №2

If you're looking to find the current location using jquery, you can utilize the .scrollTop() function. For more information on this topic, check out the question linked below:

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

Once you have that sorted, all that's left is resizing your logo :)

Answer №3

Including jQuery in your question tags was a good idea, even though you're not currently using it here (which is perfectly fine). If you decide to experiment with jQuery, you can try implementing something along these lines:

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

Make sure to update your HTML code like this:

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

Alternatively, I prefer using images as background elements defined in CSS rules. You could create a CSS rule like:

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

This approach helps in keeping your code organized and easily maintainable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with cross-origin in Salesforce reply (Access-Control-Allow-Origin)

While attempting to retrieve records from Salesforce using external local files via JS, I encountered an issue. Although I can see a response in the network tab, the console displayed the following error message: "XMLHttpRequest cannot load . No 'A ...

JQuery is unable to initiate a keyup event

I am currently utilizing jQuery in a web application. On one of my pages, I have set up an event listener for keypresses as shown below: document.addEventListener('keyup', function (event) { event.preventDefault(); var key = event.k ...

Infinite layers of options in the dropdown navigation bar

I am facing an issue with a dynamically generated unordered list that I want to turn into a dropdown menu. The challenge is that I do not know how many levels there will be, and I only want to display one level at a time. Here is what I have tried so far ...

Reactjs encountering issues loading css file

Currently, I am working on a project in Reactjs with Nextjs. To add CSS to my project, I have stored my CSS files in the 'styles' folder. In order to include them, I created a file called '_document.js' and implemented the following cod ...

Display the variable value in an HTML format following the submission of a request to an API using NODE JS, express, and jquery

Seeking assistance with completing a straightforward task: Creating an HTML AJAX link that triggers a Node.js API call to retrieve a value, wait for the response, and then display the value in HTML, JS, or PHP. After clicking on the "Get My Value" link be ...

After clicking the submit button, how can I eliminate the following: "config.php?username=++psw&Text=psw&submit=send?" and remain on the same page?

Whenever I hit the submit button on my form, PHP completes its task but instead of staying on the page (or simply reloading it), I am redirected to the same URL with '/config.php?username=technologies.%0D%0A++&submit = Send ". Is there a way ...

Is it possible for a user to change the data stored in sessionStorage variables?

Incorporating client-side JavaScript into my project to save certain variables using Web Storage - specifically, the sessionStorage. However, uncertainty exists regarding whether a user holds the capability to alter these variable values. If this is indee ...

Show a grid layout with adjustable sizing and elements centered in the middle

When dealing with a layout like the one below, how can we ensure that elements are centered within the wrap container? The margins around the elements should be flexible but at least 14px. .wrap{ display: grid; grid-template-columns: repeat(auto-fi ...

Restrict the height of posts created in the summernote editor

My goal is to create a structured page application using summernote. When using summernote, a div with contenteditable=true is appended to the body to allow users to add content. However, I want to set a fixed height for this div so that users can only ent ...

Ways to retrieve information from a different website's URL?

Having a bit of an issue here. I'm currently browsing through some reports on webpage #1 () and I have a specific requirement to extract the object named "data" from webpage #2 (). However, the code I've used seems to fetch the entire webpage ins ...

Having Trouble Changing CSS with Rails Link_to CSS ID

While following the ruby on rails guide, I came across a specific way to write link_to's with a css id: <%= link_to "About", about_path, id: "third" %> I also attempted: <%= link_to ("About", :id => "third"), about_path %> Although ...

Displaying both items upon clicking

Hey there, I'm having an issue where clicking on one article link opens both! <span class='pres'><img src='http://files.appcheck.se/icons/minecraft.png' /></span><span class='info'><a href=&apo ...

What is the best way to utilize Selenium with Python for choosing an item from a dropdown menu when the choices are contained within non-interactable <div> elements?

I am currently working on a program that navigates through the well-known website using selenium automation. However, I have encountered an obstacle on the second page where there is a dropdown menu prompting users to select a top-level domain. The dropdo ...

The URL is unresponsive following the deployment of the production build in tailwind

The image URL in my project is functioning correctly in the VITE server environment before the production build. However, after the production build, it fails to display the correct path of the image in the HTML. All other images are displaying properly ex ...

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

Unable to pinpoint the source of the excess spacing within a form field

There appears to be some extra space in the text field of my form, extending beyond the container margin. Please refer to the image and JSFiddle http://jsfiddle.net/GRFX4/. Any thoughts on what might be causing this issue? Thank you. HTML: <div id="co ...

Get an array of JSON values using a jQuery function

How can I create a jQuery function that imports a JSON value and returns an array when called? I have written the following function, but it is returning an empty array. The JSON file I am working with is very basic, similar to this example: { "fruit": [ ...

Tips for updating and transferring a variable within a callback function

I have implemented a function using the SoundCloud API that retrieves a song URL, obtains the associated sound ID from the API, and then passes that ID to a callback for streaming purposes and updating the page. The data is successfully retrieved from the ...

Image expansion

I have a container element div that holds various content of unknown length. How can I add a background image that extends the entire length of the container since background-images do not stretch? I attempted to use a separate div with an img tag inside. ...

Different ways to pause and restart slides.jquery.js

UPDATE July 4: I am still facing difficulties with this problem. It seems that creating a function to stop the slideshow based on the 'playing' class might solve it, but I am unsure how to implement such a function. I am utilizing slides.js on a ...