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

Developing a sliding menu with AngularJS

Currently, I am developing an AngularJS application. One of the features I am working on involves having a menu at the top of my page that, when an item is selected, will slide down to reveal content specific to that selection in the same area as the menu. ...

Preventing users from inputting the symbols "+" or "-" in a React JS input field

Essentially, the input field should only accept values between 1 and 999 Input Field : <input type="number" value={value} onChange={this.props.onViltMaxUserChange} min="0" max="999" /> onChange : onViltMaxUserChange = _.throttle(e = ...

Summing Values with Linq.js Filter

Can you apply a filter in Linq.JS using SUM? This is my attempt: var query = Enumerable .From(self.data()) .Where("$$.Sum($.percent) > 100") .ToArray(); Issue encountered: linq.js: Uncaught TypeError: $$.Sum is ...

Enhancing Application Views in ExtJS Classic 7.3.0 using .scss Style Sheets

Referencing the guidelines provided in this resource for theming: In order to create CSS rules specific to an application view, you need to generate an .scss file within the same directory and with a matching base name as the view. For instance, if you w ...

Should custom directives be utilized for templating within AngularJS applications?

Thinking about optimizing my AngularJS app, I'm considering creating custom directives for the navigation bar and footer which appear on every page. This way, I can easily modify them without having to update each individual html file. Do you think th ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...

When I click on a link to redirect it, I am confronted with a bizarre rectangle that

When attempting to create redirects using images, I encountered a small issue. Take a look at this screenshot: This is the item in question: <p><div><a title="Home" href="/home"><img src="/icons/home.svg" ...

What could be causing the tooltip to not function properly with data-html="true"?

I am having trouble with customizing a tooltip. The data-html="true" attribute is not working as expected, and I can't seem to figure out what the issue is. .tooltip-custom { display: inline; position: relative; } ...

Tips for successfully implementing Typeahead with Bloodhound and a JSON response

Looking for guidance on integrating typeahead.js with bloodhound.js to leverage my JSON data structure. My goal is to implement a type-ahead feature utilizing a preloaded JSON object that remains accessible. Here's the breakdown: The Data/All URL res ...

Preventing User Input in Autocomplete TextField using React Material UI

Currently, I am utilizing the Material UI component Autocomplete to display options. However, I would like for Autocomplete to function more like a select dropdown, where users do not need to type anything to receive suggestions. Is there a way to modify A ...

What is the best way to implement a CSS Style specifically for a glyphicon icon when it is in keyboard focus?

I have a particular icon representing a checkbox that appears as a glyphicon-star. It is designed to display in yellow when focused on by the keyboard navigation. This feature is intended to help users easily identify their location on a page. However, an ...

Is there a method to ensure that the window event always gets triggered before any other events?

Is there a way to make the window event trigger first when clicking on #myDiv? (function ($, w, d) { $(d).ready(function () { $(w).click(function() { alert('window has been clicked'); }); $('#myDiv').cl ...

What is the best way to position two elements floated to the right in separate rows within a single row?

Having trouble with a web design issue. I am currently working on a website and trying to format an input field with a label so that the label sits on top of the input while floating to the right. However, I'm encountering difficulties as the elements ...

When selecting a new tab in HTML, the current page position remains unchanged. However, I would like the page to automatically scroll to the

In the design of my website, I have incorporated buttons that are linked to various pages using navigation tabs. However, when these buttons are clicked, the view maintains its position on the new page (e.g., halfway scrolled through the page). Instead o ...

Learn the best way to utilize a stylus in Vue files to interact with JavaScript variables

For instance: <script> export default { data() { return{ varinjs: 1, } } } </script> <style lang="stylus"> varincss = varinjs body if varincss == 0 ba ...

Incorrectly resolving routes in the generate option of Nuxt JS's .env configuration file

Having trouble using Nuxt JS's 2.9.2 generate object to create dynamic pages as static files by referencing a URL from my .env file: nuxt.config.js require('dotenv').config(); import pkg from './package' import axios from 'a ...

Give a jQuery Mobile flipswitch a new look

Currently, I am using jQuery Mobile and recently attempted to refresh a flipswitch. However, upon executing the code $("#flipEnabled").slider("refresh");, I encountered an error in the console: Uncaught Error: cannot call methods on slider prior to initial ...

Having trouble with importing files from a different folder in a React Typescript project

I have a specific folder arrangement set up https://i.sstatic.net/GFOYv.png My goal is to bring both MessageList.tsx and MessageSent.tsx into my Chat.tsx file // Chat.tsx import React from 'react' import {MessageList, MessageSent} from "./ ...

Tips for incorporating additional filter criteria into a jquery script

I am currently utilizing a jQuery script to filter data based on date periods. However, I now need to include an additional filtering criteria for the "POSITION" column. Since I lack expertise in jQuery, I would rather accomplish this using plain vanilla J ...

Unable to locate the internal/fs module, current solutions are proving ineffective

Every time I try to run my project, I encounter the same issue despite downgrading my node version to 8.4.0 (npm version 5.3.0). I have tried various solutions such as removing the node_modules, running npm cache clean --force, and then npm install, but no ...