Showing a property only as you scroll through the page

Seeking assistance on creating a scrolling effect for a box shadow property using HTML, CSS, and JS.

The goal is to have the shadow appear with a subtle transition while scrolling and then disappear when scrolling stops.

Here's the code I've been working with:

<head>
    <title>website</title>
    <link href="style.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
    <div id="mySidenav" class="sidenav" onscroll="scrollShadow()"></div>

CSS

.sidenav {
height: 100%;
width: 280px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: skyblue;
overflow-x: hidden;
transition: 0.5s;
padding-top: 10px;
}

JS

function scrollShadow() {
document.getElementsByClassName("sidenav").style.boxShadow = "3px 0px 10px black"; 
}

Any advice or solutions would be greatly appreciated!

Answer №1

If you're finding it difficult to manage the style attribute, especially when dealing with multiple elements, consider applying a class to body and using CSS to style the elements instead.

(function iife() {
    var body = document.body;
    var timer;
  
    window.addEventListener('scroll', function onScroll() {
        clearTimeout(timer);
        body.classList.add('scrolling');
    
        timer = setTimeout(function removeClass() {
        body.classList.remove('scrolling');
        }, 150);
    }, false);
})();
*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

#container {
  width: 100vw;
  height: 5000px;
  background: lightgrey;
  transition: background 5s;
}

.scrolling #container {
  background: red;
}

#fix {
  position: fixed;
  top: 50px;
  left: 50px;
  height: 120px;
  width: 20px;
  background: white;
  transition: all 300ms ease 0s;
}

.scrolling #fix {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.35);
  transform: translateY(-3px);
}
<div id="container">
  <div id="fix"></div>
</div>

Answer №2

Using jQuery, you can implement a scroll method like so:

<script>
   $(function(){
       $(window).scroll(function(){
           if($(window).scrollTop()>=40){
                /*perform action */
               addShadowEffect();
           }
       });
   });

   function addShadowEffect() {
       document.getElementsByClassName("sidenav").style.boxShadow = "3px 0px     10px black"; 
  }
</script>

Answer №3

To start off, it's important to avoid mixing CSS with JS as it doesn't belong there. The recommended approach is to assign a class to the body element and style it with CSS accordingly. Determining when the user stops scrolling isn't natively possible, so setting a timeout that reverts changes unless the user scrolls again is a workaround. Ensure the window is fully loaded before targeting elements that may not exist yet. Below is a sample code snippet that demonstrates this:

window.addEventListener('load', function(){

    var timeout = null;
    var body = document.querySelector('body');
    var scrollClass = 'scrolled';

    window.addEventListener('scroll', function(){
        clearTimeout(timeout);
        body.classList.add(scrollClass);

        timeout = setTimeout(function(){
            body.classList.remove(scrollClass);
        }, 250);
    });

});
body {
  height: 2000px;
}

.sidenav {
    height: 100%;
    width: 280px;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: skyblue;
    overflow-x: hidden;
    padding-top: 10px;
    transition: box-shadow 500ms ease-in-out;
}

.scrolled .sidenav{
    box-shadow: 3px 0px 10px #000;
}
<div class="sidenav"></div>

This solution should meet your requirements.

Sincerely, Tom

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

What steps are involved in adding an image to an autocomplete script?

I need help adding an image to my autocomplete script. Below is my code that I'm struggling with. My Controller: function getsearch($c_id) { $searchTerm = $_GET['term']; $query = $this->db->query("SELECT state_name FROM state ...

Unable to choose from the dropdown menu

I'm having trouble with selecting options on a selectbox when the select option is overlapping my menu. The menu I'm using is a jQuery Plugin. When the select box overlaps the menu, the options are hidden. I tried adjusting the z-index of my div ...

Using jQuery to dynamically populate select options based on JSON data

I have been testing and searching for a solution to my issue, but it still doesn't work. Any help would be greatly appreciated. I have three select options implemented in PHP like this: <div class="control-group" id="merkPrinter"> <label cl ...

Attempting to troubleshoot and execute knex commands within the package.json file

At the moment, I am utilizing a knex project that was crafted by an individual on GitHub. I've encountered some issues with the package.json file, which should ideally simplify the execution of knex commands: { "name": "database", "version": "1. ...

For each item they possess, attach a "!" at the end

Given an array, I am trying to use map to add an exclamation mark to each item in the array. For example: Before - items: ["ball", "book", "pen"] After - items: ["ball!","book!","pen!"] const array = [ { username: "john", team: "red", score: 5 ...

Utilize SVG background with transparent text for a clear view of surrounding content

I'm looking for a way to overlay a video with a semi-transparent black div that includes text and a button, while still allowing users to see the video playing behind it. I previously achieved this using a PNG image but now need to apply the effect to ...

Is it possible to extract only the Bolded Text and store it in a String Array within a Spanned String

I need help with extracting bolded text from my paragraph-long stories that are saved as spanned strings in an EditText. The regular text is interspersed with a few bolded words here and there, and I want to be able to search through the spanned string a ...

Enhancing CSS with Additional Properties

As a web developer, I recently had the opportunity to explore the new LOGIN PAGE preview of GMAIL and was very impressed with the Sign In button's UI. After examining the Page's CSS, I discovered some interesting properties, such as: **backgroun ...

Can you explain the significance of this specific form of variable declaration?

Have you ever been in a situation where you receive some code that actually works, but you're not sure how it's working? For example, what exactly does this declaration method accomplish? const { actions: { createRole, updateRole } = {} } = prop ...

Merging Vue props with v-for for powerful data handling

Below is an example of my child component HTML: <div v-for="(input, index) in form.inputs" :key="index"> <div> <input :name"input.name" :type="input.type" /> </div> </div> JavaScript (Vue): <script> export d ...

Issues with Sound Not Playing When Button is Clicked in Python Flask

My goal is to trigger an audio sound when the Delete button is clicked. I've created an external JavaScript file and successfully linked it with Flask. index.html <a href="/delete/{{todoitem.item_id}}" class="btn btn-danger" onclick="playDelSound ...

Node.js - Creating seamless integration between Sequelize model JS and controller TS

Having trouble making my User.js model recognized inside my UserController.ts with sequelize in TypeScript. Edit: Unable to change the file extensions for these files. In the await User.findAll() part, an error occurs when running on the server, stating ...

Achieving Perfect Alignment in Dreamweaver: Crafting a Stylish Header Container

Hello, I am currently working on a Dreamweaver site and have created a CSS style sheet within my template that includes a div tag called #HeaderBox. My goal is to make this box 40% of the screen's size, with specific pixel dimensions if necessary. I a ...

Finding your current location and address using HTML5 geolocation

My web application utilizes HTML5 geolocation to obtain latitude and longitude coordinates. I am looking for a way to convert these coordinates into actual addresses whenever possible. Once that is done, I need to save the address information into a MySQ ...

`Enhance Image with a Fresh Hue`

Let me explain my dilemma: I'm dealing with a two-tone png image - one tone is black and the other is transparent. Right now, I'm relying on the background color attribute to dynamically change the color of the transparent section. However, I ...

Tips for deleting an HTML row and removing an entry from a MySQL database through the use of AJAX

Utilizing a mix of HTML, PHP, Javascript, and AJAX, I am creating an HTML table populated from a MySQL database. The goal is to implement a functionality where a row can be removed from both the table and the database using a delete button. Here's wha ...

Turbolinks gem causing ShareThis to malfunction

After adding the turbolinks and jquery-turbolinks gems to my project, I noticed that my ShareThis button no longer pops up when clicked. The ShareThis scripts currently included in my application.html.erb head are: <script type="text/javascript">va ...

Elevate the index of the name attribute for an input field within a dynamically generated form

In my scenario, I have created a form that includes indexed input fields for username and level: <form> <table> <tr class="trToClone"> <td> <label>Username:</label> <input type="text" name="usernam ...

Is it possible to safeguard undisclosed data in browser console?

Can JavaScript be employed to prevent users from editing hidden fields through the browser console? ...

Issue arises where multiple asynchronous functions cause infinite re-rendering due to the shared loading state

Currently, I am integrating zustand 4.1.5 into my React application. Upon clicking the LogDetails tab, two asynchronous functions with identical loading state settings are triggered simultaneously, leading to an endless rerendering cycle and causing the & ...