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

Utilizing LESS for Mixing

I've been diving into the official LESS documentation (version 1.5) and I'm struggling to grasp how I can import a reference to another CSS file to utilize its content in my own stylesheet. For instance: stylesheet.less @import (reference) "boo ...

What is the reason for hasChildNodes returning true when dealing with an Empty Node?

When the user clicks on purchase and the cart is empty, there should be an alert. However, it seems that no response is triggered. Upon running the program, an error message appears stating that it cannot read the property of addEventListener which is unde ...

Align the content of a collapsed bootstrap row vertically

In a row, I have two columns, each containing their own row. When the page width hits the 'xs' break-point, the left column's row will stack its columns on top of each other. The right column is taller than the left column, which leaves a l ...

When working with basic shapes such as "rect" or "circle," the inline SVG may not be displayed

This is the code we are using to style our checkboxes: .checkbox-default { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 22px; height: 22px; background: url('data:image/ ...

determining the overall page displacement

I'm working with this code and I need help using the IF condition to check if the total page offset is greater-than 75%. How can I implement that here? function getLocalCoords(elem, ev) { var ox = 0, oy = 0; var first; var pageX, pageY; ...

unable to retrieve the latest scope value following the completion of the ajax request

I attempted to use the code below, but despite searching for answers and solutions involving $apply and $timeout, nothing seemed to work in my case. I encountered several errors along the way. JS: var app = angular.module("test",[]) app.config(function($ ...

Utilize formData to upload an image to a database with ajax

I'm struggling with the process of uploading an image from an HTML form. The goal is for the form to send the image name along with other data to a PHP page. Instead of using the serialized function, I opted for formData as it has the capability to h ...

What prompts certain individuals to convert their asp.net pages into HTML pages before publishing?

Recently, I was informed that there is a possibility of working on a project involving ASP.NET 3.5 and C#. A colleague suggested that when we publish the site, we should convert all pages to HTML. This means instead of www.test.com/Page.aspx, it would be w ...

Issues arise with the functionality of custom jQuery sliders

I'm attempting to create a bootstrap panel slider using my own jQuery code, but it's not functioning as anticipated. My Objective: I have two links for "previous" and "next", and three panels with distinct headings. When the "previous" link is ...

Is it possible to dynamically alter the href attribute of a hyperlink within a Twig template in Symfony 2?

Developing a menu for my website has been occupying my time lately, sparking numerous inquiries about its functionality. Essentially, I aim to create a menu with a select option containing all my projects. By clicking on either the modify or delete button, ...

What is the best way to center the input on the page?

Does anyone know how to align the <input type="text"> in the center? I'm trying to create a login form but having trouble with positioning the input element. ...

Please furnish request.body with all necessary details for nodemailer, excluding the email address

I'm currently working on a contact form for my node.js and express web app, utilizing nodemailer. Everything seems to be functioning correctly - the server is recording information and sending it to the specified email address. However, there is an i ...

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

What are some methods to design distinct angular ui bootstrap dialogs?

Is there a way to customize angular-ui bootstrap modal dialogs so that they have distinct colors and sizes from each other? I can style them globally for the site but not individually. I came across a similar question, but it only addresses changing all d ...

What is the best way to align the navigation bar to the left using bootstrap?

I'm having trouble creating a navigation bar for my website using bootstrap 5. I tried to move the bar to the left by adding the class margin left auto (ml-auto), but it didn't work as expected. Can someone help me figure out why? Thank you in ad ...

Converting CSS into jQuery

I am exploring ways to create a collapsible section with arrow icons (right and down arrows) in jQuery or JavaScript. Can anyone provide guidance on how to convert my CSS styling into jQuery code? Below is the jQuery approach I have attempted: $(document ...

I'm having trouble getting my jQuery click handler to work

Here is the HTML content within my Sharepoint 2010 Web Part project: <html> <h1>Travel Form Assistance</h1> <div id="preTravel" name="preTravel"> <h2>Pre Travel</h2> <img id="imgPreTravel" name="imgPreTra ...

What is the best way to incorporate multiple input boxes into a single alertbox for repeated use?

I attempted to use the same alertbox for 3 different input elements by converting it into a class and using getElementsByClassName, but unfortunately, it did not work as expected. Here is what I tried: <input type="text" class="form-control date notif" ...

Use jQuery to replace this color with that color in CSS every time it appears

I have numerous div elements, some with a background-color: #aaa, others with font color: #aaa, and some with border-color: #aaa. There are also divs with various other colors. I am looking to update these colors (#aaa) to #ccc throughout the CSS. While ...

Solution for tables extending beyond the navbar and footer issue

My table is extending beyond the width of both the navbar and footer. Is there a way, using HTML and CSS, to make the navbar and footer expand in width to match that of the table? Most solutions I've found focus on formatting the table instead of addr ...