Javascript Challenges in Wordpress

Looking to create an element on a Wordpress site where content starts partway down the screen and then sticks to the top while scrolling. I've tried different approaches without success. My latest attempt involves using Javascript to add and remove a class from the content to achieve this effect.

The script I'm using is:

jQuery( document ).ready(function($) {
    alert( "test1!" );

    var wrap = $("#wrap");

    wrap.on("scroll", function(e) {

        if (this.scrollTop > 147) {
            wrap.addClass("fix-search");
            alert("test2");
        } else {
            wrap.removeClass("fix-search");     
        }

    });

});

The file is enqueuing correctly as the first test alert ("test1") triggers, but "test2" doesn't fire when scrolling down. This same code worked in a modified version on Codepen (http://codepen.io/anon/pen/NqKKVN), so it seems there might be some issue with Wordpress interacting with Javascript.

If anyone has a solution that works well with WordPress or can help troubleshoot the above code, I'd appreciate it!

EDIT: Issue resolved. For anyone facing similar problems, the code that finally worked for me was:

jQuery( document ).ready(function($) {

    var scrollTop = $(window).scrollTop();

    function scrollUpdate() { 

        var scrollTop = $(window).scrollTop(); 
        
        var wrap = $("#menu-all-pages");

        if (scrollTop > 147) {
            wrap.addClass("fix-search");
            console.log("Menu at top");
        } else {
            wrap.removeClass("fix-search");
            console.log("Menu at set point");       
        }

        console.log(scrollTop);
    }

    window.onscroll = scrollUpdate;

});

Answer №1

A few years back, I successfully integrated a similar solution on my blog. The implementation involved using the following script:

  1. Define a variable named scrollTop to store the pixel value scrolled from the top of the window.

To achieve this, I utilized a jQuery function called scrollTop on the "window" object to capture the vertical scroll position. This method worked seamlessly on Wordpress as well.

var scrollTop = $(window).scrollTop();
  1. Create a function named scrollUpdate to update the scroll value as needed.

Within this function, include the logic for monitoring the scrollTop value and applying corresponding styles or actions.

function scrollUpdate() {
   var scrollTop = $(window).scrollTop();
}
  1. Ensure that the scrollUpdate function is triggered each time the page is scrolled.

    window.onscroll = scrollUpdate;

Give it a try yourself!

Tip: Consider using show/hide functions instead of adding complete CSS classes for better performance.

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

Using the native functionality, submitting a razor form with JQuery AJAX in MVC6

Is there a specific method to submit a form using jQuery AJAX in MVC6 while still utilizing the Auto Binding functionality of ASP.NET MVC? In previous versions of MVC, one could use jquery.unobtrusive-ajax and simply utilize @using (Ajax.BeginForm("SaveDa ...

Is there a way to automatically increase a value by clicking on it?

Check out this code snippet I'm working with: let funds = document.createElement('funds') funds.style.color = 'green' funds.style.textAlign = 'center' funds.style.fontSize = '50px' funds.style.backgroundCol ...

Show every element of an array except for the selected index using Javascript

I'm curious, is there a way to display array indexes in reverse order? Let's consider the following array: var color = ["red", "green", "blue", "yellow"]; console.log(color[2]); Normally, the console would display "blue", right? But what if we ...

What is the best location to place an HTML wrapper element within a React Project?

Just diving into the world of React, I've embarked on a simple project with bootstrap My goal is to reuse a specific HTML structure: <div className="container"> <div className="row"> <div className="col-lg-8 col-md-10 mx-auto"&g ...

Adjusting the width of a div element horizontally in Angular 4 and

As someone new to Angular 4, I've been attempting to create a resizable div (horizontally) without success. My goal is to be able to click and drag a grabber to resize the text area horizontally. However, in the example provided in the link below, the ...

Is there a way to deactivate a JavaScript function on a specific webpage using CSS?

I've implemented a JavaScript function that triggers a pop-up alert whenever a user attempts to navigate away from the site by clicking on an external link: $("a[target='_blank']").click( function() { return confirm('Please don&apo ...

Protecting against overflow for text inside a container that changes when hovered over

There is text displayed on top of an image within a div container that functions as a link. <a href="https://link.com" style="color:white"> <div class="thumbnail"> <img src="image.jpg" clas ...

What is the difference between adding the .js extension when importing files in TypeScript versus Angular imports?

When working on my TypeScript project, I've encountered an issue where I need to include the *.js extension when importing files. If I omit the extension, the project will build successfully but fail at runtime in the browser due to file not found err ...

"Unpredictable behavior observed with useSWR hook or potential issues with outdated closure function

Within my React functional component, I have implemented a Lesson Video Player that functions similarly to Instagram Stories. Each lesson contains videos ("clips") with interactive elements that trigger a multiple-choice quiz for the user. Below is a simpl ...

Implementing Event Handlers Based on State Changes

I'm struggling to create a grid with hover effects where hovering over a grid-div should change the background-color, and hovering again should revert it back. The issue I'm facing is that once I remove the color by hovering, I can't apply i ...

Beginner in html, css, and javascript: "Tips for saving jsfiddle demos?"

Recently, I developed an interest in JavaScript and CSS and came across some impressive examples on jsfiddle. I was wondering if there is a way to "export" these examples to my computer. Simply copying and pasting doesn't seem to work. How can I modi ...

How to transfer the application version from package.json to a different non-JSON file in Angular and node.js

While developing my Angular application, I encountered a task where I needed to extract the version number from the package.json file and transfer it to a non-json file. The content of my package.json file is as follows: { "name": "my app ...

Can you explain the function of the forward slash in the HTML img tag?

Currently, I am in the process of learning html/css by following the tutorial provided by W3Schools.com. The part of the code that is causing me some difficulty can be found at http://www.w3schools.com/css/tryit.asp?filename=trycss_vertical-align Specific ...

Converting text/plain form data to JSON using Node.js - step by step guide

I am currently working on a Node.js application to execute a POST call to an API for placing an order. However, the data I receive in our app is in text/plain format and not JSON. This is the current format of the data: TypeOrder=buy Coin=BTC AmountCoin= ...

What is the significance of mapping transformations on objects within MongoDB?

I encountered an issue. Every time I try to create a map in MongoDB, for example a shop, guildID: id, ownerID: owner_id, _premium: 0, Moderation:{ auto:false, prefix:'k!', muter ...

Statement after post is not yielding any result

Below is a javascript function that I'm struggling with: function loginsubmit() { var url = "../php/loginsubmit.php"; var data = ""; ajaxRequest(url, "POST",data , true, insertNewBody); } This function is responsible for sending an ajax ...

Tips for waiting for a Promise to resolve before returning a new Promise

In the process of developing a web application tailored for crafting retail signage, I have integrated Firestore to manage pertinent information about these signs. One specific functionality I am working on is enabling users to effortlessly remove all exis ...

Send data via POST method using jQuery AJAX in MVC2

I am currently working with MVC2 and attempting to send data using jQuery ajax. Below is my JavaScript code: $.ajax({ type: "POST", url: "Data", data: { processName: "MyProc", startDate: "2015-08-01 16:00"}, success: function(data) { ...

Issue with Nodemailer OAuth2 2LO authentication when deployed on Heroku

const { EMAIL_FROM, EMAILS_TO, USER, GMAIL_CLIENT_ID, GMAIL_PRIVATE_KEY } = process.env; let transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { type: &a ...

What could be causing a timepiece to be one tick off in vue.js?

I am looking to synchronize the height of one element with another, where the content in the second element changes dynamically. Below is an example code snippet (also available on JSFiddle): var vm = new Vue({ el: "#root", data: { growingTex ...