Display logo when website has been scrolled

On my website, I want to display a logo in the header only when the site has been scrolled. I attempted to accomplish this with JavaScript:

if(document.getElementById("div").scrollTop != 0){
  document.write("<img src='logo.jpg'>");
}

However, my code was unsuccessful. Does anyone know how to achieve this?

Answer №1

To implement a scroll event listener in JavaScript, use the code

window.addEventListener('scroll', callback)
and then assign the value "block" to the img element's property.

window.addEventListener('scroll', function(e) {
  if (document.getElementsByTagName("html")[0].scrollTop > 5) {
    document.getElementsByClassName('imgHeader')[0].style.display = "block";
  } else {
    document.getElementsByClassName('imgHeader')[0].style.display = "none";
  }
});
.imgHeader {
  height: 100px;
  width: 100px;
  display: none;
}

div {
  height: 1000px;
}

header {
  position: fixed;
  top: 0;
  width: 100%;
}
<header><img class="imgHeader" src="https://material.angular.io/assets/img/examples/shiba1.jpg" /></header>
<div></div>

Answer №2

Give this a try

$(document).on("scroll", function() {
  if ($(document).scrollTop() > 5) {
    $(".below-top-header").addClass("show-class");
  } else {
    $(".below-top-header").removeClass("show-class");
  }
});
.content {
  height: 500px;
}

.show-class {
  position: fixed;
  display: block !important;
}

.hide-class {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <div class="below-top-header hide-class">
    Image
  </div>
</div>

Answer №3

It seems like incorporating some JavaScript is necessary to achieve the desired functionality.

Below is a simple code snippet demonstrating the approach I employed:

  • Begin by including the logo within the html code, but with its CSS set to display: none,
  • Utilize
    window.addEventListener('scroll', callback)
    to toggle the display property from none to block when the user scrolls down the page (i.e., when
    document.documentElement.scrollTop > 0
    ).

var logo = document.getElementById('logo');

window.addEventListener('scroll', function(e) {
  if (document.documentElement.scrollTop > 0) {
        logo.style.display = 'block';
  }else logo.style.display = 'none';
});
#logo {
  display: none;
  position: fixed;
  top: 0;
  background: #aaa;
}

#page {
  background: #ddd;
  height: 2000px;
}
<div id='logo'><img src='http://placekitten.com/200/50'></div>
<div id='page'>Start of page<br>Try to scroll down</div>

I hope this solution proves useful to you.

Answer №4

To ensure your code is executed when the user scrolls, you must add a scrollListener to the window object. This will prevent it from only running on page load.

For more information on EventListeners, visit: https://developer.mozilla.org/de/docs/Web/API/EventTarget/addEventListener

window.addEventListener('scroll', function(e) {
    //perform actions when the window is scrolled
});

Keep in mind that the event will be triggered every time the user scrolls.

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

The sidebar in Semantic UI does not have a specified height for the form segment

Need help troubleshooting a button that slides out a vertical sidebar. I want to include a short form for users to input search queries within the sidebar. The issue seems to be with the heights of #search-sidebar and .ui.form.segment. Here is the code s ...

Adding individual flag icons for each country in your Datatables can be a significant enhancement to

Below is the code snippet in JavaScript with flags: <script type="text/javascript"> $(document).ready(function() { var dataTable = $("#example").DataTable( { processing: true, bSort: false, ...

Unable to fetch data in CakePHP 3.x controller using jQuery AJAX POST

I've been searching everywhere and unfortunately, I can't seem to figure out why the data is not being sent to my controller when posting via ajax. Here's the jQuery code snippet: var newDate = {}; newDate['start' ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

"Exploring the possibilities of Sketchfab through an AJAX JSON

Currently, I am on a quest to gather the URL for the thumbnail of a Sketchfab model. To access this information, you can visit: Upon visiting the above URL, all the necessary details are visible to me. My next step involves making an AJAX call to dynami ...

Pair objects that possess a specific attribute

I have a HTML snippet that I want to modify by adding the CSS class HideEdit to hide specific columns. <th class="rgHeader" style="text-align: left;" scope="col" _events="[object Object]" control="[object Object]" UniqueName="Edit"> This particular ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Tallying the number of messages on Facebook

Greetings everyone! I have been utilizing the Facebook JS SDK to retrieve the number of messages sent. Below is the code snippet: <script> function statusChangeCallback(response) { console.log('statusChangeCallback'); console.log ...

Empty req.params in nested ExpressJS routers

I have a unique routing system that relies on the directory structure of my 'api' folder to automatically configure routes. However, I encountered an issue where the req.params object is undefined in the controller when using a folder name as a r ...

Unusual glitch with paint/rendering in Safari while navigating through a lengthy list of content

Encountering a peculiar problem where a page displaying a grid of boxes is experiencing issues in Safari, Chrome on iPhone 11 Pro, iPhone 13 Pro, and Chrome on Pixel 4a. Other devices are not affected. Symptoms include unresponsiveness and blank sections a ...

Navigating the Google Maps API: Implementing Scroll Zoom to Focus on a Single Marker

I'm looking for a solution for my project where the scroll zoom function will focus on zooming in on a marker or specific point rather than defaulting to the cursor. The current behavior is that the scroll zoom always centers on the cursor. Can anyone ...

Updating item information within an array in Vue.js

I'm currently working on integrating an edit feature into a task application using Vue JS. My issue lies in the fact that I have a click event assigned to the edit button - @click="editShow" which displays input fields for editing all items instead ...

Word.js alternative for document files

I'm on the lookout for a JavaScript library that can handle Word Documents (.doc and .docx) like pdf.js. Any recommendations? UPDATE: Just discovered an intriguing library called DOCX.js, but I'm in search of something with a bit more sophistic ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...

Sequelize synchronization does not generate the database table

I am currently working on a project with the following directory structure: ├── index.ts ├── package.json ├── package-lock.json ├── src │ ├── controllers │ ├── models │ │ └── repository.ts │ ├ ...

Exploring Angular.js: Finding the correct path in a JSON array

Within my Angular application, I have a $scope variable defined as follows. $scope.roleList2 = [ { "roleName" : "User", "roleId" : "role1", "children" : [ { "roleName" : "subUser1", "roleId" : "role11", "collapsed" : true, "children" : [ ...

generate a flexible div that adjusts its height based on the size of the browser window

Is it possible to create a div layout structured like this: <div_wrapper> <div_header> </div_header> <div_content> </div_content> </div_wrapper> Upon page load, the div_header o ...

Is there a way to alter multiple classes using hover effect on a single class without the use of JavaScript, only employing

Hello there! I have a question about applying styles to specific classes when hovering over certain elements. Unfortunately, I am unable to make changes to the HTML files and can only work with the CSS file. Take a look at the image below for reference: ht ...