Using Jquery to encase an element in a div while scrolling down and removing it while scrolling up

After some experimentation, I've managed to wrap an element inside a div using jQuery. My next challenge is to wrap it as you scroll down and unwrap it as you scroll up.

Do you think this is achievable?

Although I have succeeded in wrapping it while scrolling down, I believe there is a flaw in the logic. The wrapping keeps getting executed repeatedly as I scroll down. It should only happen once I scroll past 500px.

Thank you for your help!

<script>


$(function() {
//caches a jQuery object containing the header element
var header = $(".show-on-scroll-wrapper");
$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 500) {
          $('.mobile-nav-toggle-label').wrapAll('<div id="showOnScrollWrapper" class="show-on-scroll-wrapper show"></div>'); 
        //the wrapping should only occur once 
    } else {
        //need to be able to unwrap the div if I scroll back to the top
    }
});

});

Answer №1

To improve efficiency, you can store a reference to the wrapping object and only wrap it if the reference is null. Then, in the else statement, simply replace the reference with its contents:

$(function() {
    // Store a reference to the header element in a jQuery object
    var $showOnScrollWrapper = null;
    var header = $(".show-on-scroll-wrapper");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();
        if (scroll >= 500) {
            if (null === $showOnScroll) {
                $showOnScrollWrapper = $('<div id="showOnScrollWrapper" class="show-on-scroll-wrapper show"></div>');
                $('.mobile-nav-toggle-label').wrapAll($showOnScrollWrapper); 
            }
        } else if ($showOnScrollWrapper !== null) {
            $showOnScrollWrapper.replaceWith($showOnScrollWrapper.html());
            $showOnScrollWrapper = null;
        }
    });
});

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

Issue: ParserError encountered due to a Syntax Error found at line 1, column 32

As a beginner in programming, I am encountering an issue. When I run "npm run build" in the Terminal to compress my project in React.js, I encounter this error. Interestingly, I have previously created another project without facing this problem, and I can ...

Choose solely the initial and concluding hyperlink within the divs

The structure I am working with is as follows: <div class="navigation_sub_item_background" id="sub_nav_2"> <div class="navigation_sub_item" id="2_1"> <a class="navigation__sub__link" href="?p=2_1"> <span> ...

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

Is it conceivable that Jquery is failing to load for an Ajax request?

I have been experiencing an issue with my jQuery code not working within Ajax requests. The jQuery plugin I am using is FancyBox which can be found at . When calling the FancyBox plugin directly, everything works perfectly and multiple links load the plugi ...

How can I access and modify objects within a state array in reactJS when using the setState() method?

Upon reviewing my code, I came across the following declaration: constructor(props) { super(props); this.state = { productArray: [{ barcode: '', name: '' }], numberOfRecords: ...

What is the proper way to write the code for this form?

I am exploring alternatives to using the html TABLE tag and struggling to create the desired layout. I have attached a screenshot showing my table design. How can I achieve the same layout using divs or spans while still maintaining vertical alignment of t ...

Disappearing Div Dilemma: The Mystery of the Responsive Design

I am currently facing an issue where two div elements (`.left` and `.right`) are not displayed vertically when the width value is less than 800px. Strangely, the `.left` div disappears when I try to adjust the width. I have shortened the code for clarity. ...

Python automation with selenium - capturing webpage content

I am utilizing selenium to scrape multiple pages while refraining from using other frameworks such as scrapy due to the abundance of ajax action. My predicament lies in the fact that the content refreshes automatically nearly every second, especially finan ...

Display/Conceal Title with Hover Effect in Fancybox2

I need assistance with hiding and showing the title in fancybox2 using the hover event. The code I have tried is not working properly. Here is my current code: $("#fancybox-wrap").hover(function() { $("#fancybox-title").show(); }, functio ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Clear the data once the checkbox has been unchecked

Within my div containers, each containing a result, there is a checkbox associated with each one. When a user clicks on a single checkbox, the value of the currently checked box is sent to another page via an ajax call. The data is then fetched and display ...

How can I apply max-width and max-height to a background image?

It seems like a simple task. I am currently transitioning my layout to become more fluid by working on creating scalable images. While using the img tag and setting max-width to 100% is effective, I am considering using a div with the image set as its bac ...

Expand Elements to occupy entire width

My CSS skills are still in the early stages. I haven't delved too deeply into it. I have a query regarding how to achieve full width for an element. I've included my code below, but the basic approach I tried using 'width: 100%' didn&a ...

An error will be thrown if you try to pass an array attribute of an object as a prop to a React component

I'm trying to grasp why passing an array attribute of a data object into a Component as a prop is causing issues. Is this due to my understanding of how React functions, or are there potential pitfalls in this scenario? Any insight would be greatly ap ...

Tips for effectively handling requestAnimationFrame

I created a unique function that both scrambles and translates text. The functionality is smooth if you patiently wait for the animation to finish before moving the mouse over to other elements. However, if you try to rush through to the next one, the prev ...

Tips for customizing the appearance of Java FX TableView column headers with CSS

I am relatively new to JavaFX and delving into CSS stylesheets, as well as using stackoverflow. I am curious about how one can customize the styling of a table column header. This is what my current column header looks like: Current appearance of my table ...

What could be causing the vue-property-decorator @Emit to malfunction in my Vue TypeScript file?

I am currently working with Typescript and Vuejs, where I have a child component called child.component.tsx import Vue from 'vue'; import Component from 'vue-class-component'; import { Emit } from 'vue-property-decorator'; ...

Ways to use jQuery to disable row form elements in the second and third columns

I need a way to deactivate form elements in the second and third columns, starting from the second row until the nth row using a jQuery selector. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> ...

Ways to divide the value of an input text box using Angular

Given the value "<HR>*10/100", how can I split it into three parts: "HR", "*", and "10/100"? HTML <input type='text' ng-model='value' ng-change="GetAngValue(value)"> {{Result}} Angular $scope.GetAngValue = function (val ...