Other options or improved suggestions for utilizing Classie

As someone who is not very skilled in coding, I often find myself stumbling my way through using javascript libraries and jquery. Recently, I came across classie.js and have been utilizing it to add classes to divs and elements in my html when they appear at a certain scroll distance on the page. This has led me to include numerous scripts in my header section to handle these class additions and removals.

<script>
function init() {
    window.addEventListener('scroll', function(e){
        var distanceY = window.pageYOffset || document.documentElement.scrollTop,
            shrinkOn = 100,
            feature = document.querySelector("#welcomediv");
        if (distanceY > shrinkOn) {
            classie.remove(feature,"welcomewish");
        } else {
                classie.add(feature,"welcomewish");    
        }
    });
}
window.onload = init();
</script>
... (more script blocks here)

(...and there are even more! If I had my way, I would probably want to add even more because of the flexibility it offers with manipulating elements by adding and removing classes. However, this approach feels clunky, messy, and incredibly hard to maintain.)

The issues I am facing with this setup are:

1) My header section is filled with cumbersome scripts. Is there a way to streamline these scripts while retaining their functionality?

2) Whenever I introduce new elements or remove existing ones from the page, I need to manually adjust the numeric values (shrinkOn) associated with each instance. This quickly becomes a nightmare. It would be ideal if I could indicate something like "when this element appears on the page" or "100px after this element appears on the page" instead of specifying a fixed pixel value for scrolling. Can classie accommodate this requirement, or should I explore alternative solutions?

Thank you in advance, and I hope this query is appropriate for discussion.

Answer №1

Absolutely, the code can easily be parameterized since all the blocks are performing the same function.

Here is how you can have an array of updates:

var scrollUpdates = [];

You can create a function to add each update (for convenience, you could also directly add them above):

addScrollUpdate(featureSelector, shrinkOn, className) {
    scrollUpdates.push({
        featureSelector: featureSelector,
        shrinkOn: shrinkOn,
        className: className
    });
}

One handler can manage these updates:

window.addEventListener('scroll', function(e){
    scrollUpdates.forEach(function(update) {
        var distanceY = window.pageYOffset || document.documentElement.scrollTop,
            feature = document.querySelector(update.featureSelector);
        if (distanceY > update.shrinkOn) {
            classie.add(feature, update.className);
        } else {
            if (classie.has(feature, update.className)) {
                classie.remove(feature, update.className);
            }
        }
    });
});

To add each update, follow this format:

addScrollUpdate("#welcomediv", 100, "welcomewish");

Combining all of this in one window load handler:

window.onload = function() {
    var scrollUpdates = [];

    addScrollUpdate(featureSelector, shrinkOn, className) {
        scrollUpdates.push({
            featureSelector: featureSelector,
            shrinkOn: shrinkOn,
            className: className
        });
    }

    window.addEventListener('scroll', function(e){
        scrollUpdates.forEach(function(update) {
            var distanceY = window.pageYOffset || document.documentElement.scrollTop,
                feature = document.querySelector(update.featureSelector);
            if (distanceY > update.shrinkOn) {
                classie.add(feature, update.className);
            } else {
                if (classie.has(feature, update.className)) {
                    classie.remove(feature, update.className);
                }
            }
        });
    });

    addScrollUpdate("#welcomediv", 100, "welcomewish");
    addScrollUpdate("#slidetext", 300, "welcomewish");
    // ...and so on...
};

However, using the window load event for this might be too late in the page load process. It's better to place the script tag at the end of the HTML, right before the closing </body> tag, and execute it immediately in an inline-invoked function expression like this:

(function() {
    // your code goes here
})();

Side note: While I'm not familiar with Classie, you likely don't need the has test before calling remove.

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 should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

Is there a way to use Node.js to automatically redirect any random string paths back to the main home page?

Is there a way to configure my basic Node.js server to use simple paths instead of query strings for user session IDs? For instance, can I make domain.com/GH34DG2 function the same as domain.com within my web app? This format seems more visually appealing ...

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

How can you utilize return values from functions within an if statement in JavaScript?

I'm facing a scenario with a simple if statement structured like this: if (gl.Node.moveUp.call(this) && this.parent._currentScene()) { // Perform an action } Both functions are designed to return boolean values. Does JavaScript evaluate this con ...

Preventing long int types from being stored as strings in IndexedDB

The behavior of IndexedDB is causing some unexpected results. When attempting to store a long integer number, it is being stored as a string. This can cause issues with indexing and sorting the data. For instance: const data: { id: string, dateCreated ...

Error message encountered: Module not found. It may not have been loaded yet

I am encountering an issue while attempting to utilize an npm module in my VUE component. I have imported the module and defined the necessary methods, but I am receiving the following error: Uncaught Error: No such module. (Possibly not yet loaded) De ...

Node.js server crashes upon automatic startup but remains stable when started manually

Currently, I am using Node.js and Socket.io to power an online chat feature. To manage the server, I have created a configuration file located at: /etc/init/example.conf The contents of this file are as follows: start on startup exec forever start /var/ ...

Buttons within the Bootstrap carousel caption cannot be clicked

I am currently designing a webpage with a Bootstrap carousel that includes a paragraph caption and two buttons. However, the buttons are not functioning as clickable links - when clicked, nothing happens. {% block body %} <div id ="car-container"> ...

Calculating the sha1 hash of large files using JavaScript in the browser without causing excessive memory usage

Is there a method to calculate the hash of large files in JavaScript without needing to load the entire file in a FileReader? Specifically, I'm interested in finding out if it's possible to stream a file and calculate its sha1 hash in JavaScript. ...

Initially, the 'display none' CSS command may not take effect the first time it is used

I am currently working on a slideshow application using jquery.transit. My goal is to hide a photo after its display animation by setting the properties of display, transform, and translate to 'none' value. Although the slideshow application work ...

Creating OneToMany references between existing MongoDB documents is a straightforward process that involves updating the relevant fields in

My first encounter with MongoDB has left me puzzled about creating references between documents that are already in the database. Unlike SQL, I am unsure how to establish relationships between collections. I have two collections: Films and Actors. The Fil ...

Is there a way to ensure that a method is always called in JavaScript after JQuery has finished loading

We recently integrated jquery load into our website to dynamically load content into a div without refreshing the whole page. However, we've noticed that in the complete function, we have to constantly re-apply various bindings. Is there a way to set ...

Deciphering a JSON array by value or key

I have a JSON array that I need to parse in order to display the available locations neatly in a list format. However, I am struggling with where to start. The data should be converted to HTML based on the selected date. In addition, a side bar needs to s ...

Version 10.0 of sails is having trouble with an undefined 'schema' when using mysql

i'm currently experimenting with sails js version 0.10.0 using the sails-mysql adapter 0.10.6 I have set up two models: Customer.js module.exports = { connection: 'someMysqlServer', attributes: { name: { type: 'string& ...

What is the method for calculating the total price based on three distinct data attributes?

I have chosen an option that calculates the sum of values with data attributes. It adds up #mark1 + #series1 + #mark2 + #series2 function validate() { var $selected = $('#mark1, #series1,#mark2, #series2').children(":selected"); var sum = ...

Error: Attempting to access 'map' property of an undefined variable in NEXTJS

I've been struggling to retrieve an image from this API using getStaticProps, but for some reason I can't seem to make it work. In my code snippet, if I add a question mark like this, the console returns 'undefined'. What could be caus ...

Learning to scrape website data involves activating a button

Looking to gather app version history from the Apple Store using Python? Specifically, from links like To achieve this, it's necessary to click on the Version History button found in the What’s New section. Below is the HTML snippet pertaining to t ...

Setting model value in Angular 2 and 4 from loop index

Is it possible to assign a model value from the current loop index? I've tried, but it doesn't seem to be working. Any suggestions on how to achieve this? Check out this link for my code <p *ngFor="let person of peoples; let i = index;"& ...

Utilize the ionicPlatform.ready() method for implementing a service factory

Within my app.js file, I have the following method: .run(function($ionicPlatform) { $ionicPlatform.ready(function() { gvi.Notifications.registerForPush(MessagesService.onNotificationResponse); }); }) Additionally, I have a factory ...

Tips for eliminating stuttering when fixing the position of an element with JavaScript

I am currently facing an issue with a webpage I created where the text freezes when scrolled down to the last paragraph, while the images continue to scroll. Although my implementation is functional, there is noticeable jankiness when using the mouse wheel ...