The code is malfunctioning on this site (yet functions perfectly on a different website)

So I have a question that may seem silly, but it's worth asking. I'm attempting to create a sticky div element that stays in place when you scroll past a certain point on the page. This is the script I have:

<script type="text/javascript">
$(document).ready(function() {
       var s = $("#sticker");
       var pos = s.position();                    
         $(window).scroll(function() {
       var windowpos = $(window).scrollTop();
         if (windowpos >= pos.top + 335) {
           s.addClass("stick");
      } else {
          s.removeClass("stick"); 
      }
   });
});
</script>

It works perfectly fine on one of my websites. But now, when I try to implement it on a new site, I keep getting an error in my console log that says: TypeError: $ is not a function. It highlights the $(document).ready(function() { part as the issue.

If I take out the $(document).ready and the closing });, it then tells me that var s = $("#sticker"); is causing the $ is not a function error.

I attempted

<script type="text/javascript>
 jQuery(document).ready(function() {
       var s = $("#sticker");
       var pos = s.position();                    
         $(window).scroll(function() {
       var windowpos = $(window).scrollTop();
         if (windowpos >= pos.top + 335) {
           s.addClass("stick");
      } else {
          s.removeClass("stick"); 
      }
   });
});
</script>

With this, it ignores the (document).ready part, but still complains about the var section not being a function.

When I remove the script entirely, there are no console log messages. What could be causing the problem? I've tried placing the code in the header, footer, even right before the

<div id="sticker">...</div>
. Nothing seems to make it work. Strangely enough, the script functions perfectly fine on another website...

Answer №1

If you are utilizing jQuery in `noConflict` mode, this means that jQuery can only be accessed by using the `jQuery` keyword instead of `$`. To regain access to jQuery using `$`, you can enclose your code within a `ready state` or an `IIFE`.

Ready State:

jQuery(document).ready(function($) {
    // access jQuery with '$' inside
});

// shorthand for the above '.ready' creation
jQuery(function($) {
    // access jQuery with '$' inside
});

IIFE:

(function($) {
    // access jQuery with '$' inside
})(jQuery);

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

An object resulting from the combination of two separate objects

After reading a helpful solution on StackOverflow about merging properties of JavaScript objects dynamically, I learned how to utilize the spread operator in Typescript. However, one question still remains unanswered - what will be the type of the object c ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...

Implementing CSS and JS for targeted elements or functions in WordPress

I am currently managing a WordPress WooCommerce website My goal is to implement bootstrap CSS and js specifically for a function on my WooCommerce checkout page. The code I have written is as follows: if( current_user_can('administrator')) { fu ...

Universal message/status/error that can be utilized in both jquery and C# programming

There are instances where we utilize the same error or success messages, as well as checking for certain statuses, in both jQuery and C#. To maintain consistency, it is ideal to define all message/status flags within a static class and access them whereve ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

Having difficulty deleting a checkbox element using JavaScript

My goal is to have a feature where users can effortlessly add or remove checkbox div elements as needed. The code I have written successfully adds and resets checkboxes, but I am encountering an issue when trying to remove them. I am struggling to identif ...

Using Vue.js and JavaScript to access a single variable across multiple class methods

I am working on organizing my custom channel logic into its own class. During the created lifecycle method, I am executing each method in the class I created. However, I am facing a challenge in retaining the instance of the socket that was created in the ...

How to locate the duplicate elements within an array using JavaScript

There are two different sets of numbers Numbers1=[ 0, 1, 2, 0, 2 ]; Numbers2=[ 0, 0, 1, 2, 2 ]; The goal is to determine the index of each element in Numbers2 from Numbers1 and create a new array like [0,3,1,2,4]; If you would like to see the code I wr ...

unable to render a vector layer in openlayers 6

Currently, I am facing an issue with displaying a vector layer on an openlayers map using the source of local geojson and gpx files in my Vuejs project. Unfortunately, even when testing outside of Vue.js, the vector layer is not being displayed. Here is t ...

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

Adjust the size of a div using jQuery while toggling text

Seeking help for expanding a div when text toggle overflows current size due to mouse click. Current issue results in text overlapping the containing div. Toggle Function: $(document).ready(function(){ $(".parents-toggle > div").click(function () { $( ...

Encountering issues with the Sequelize Model.prototype.(customFunction) feature malfunctioning

While attempting to define a customFunction within the Sequelize model, I encountered an error: TypeError: user.getJWT is not a function at User.create.then (/projects/test/a/app/controllers/UserController.js:22:29) Below is the code snippet from ...

Creating a slanted polygon div that adjusts to different screen sizes: a step-by-step

Looking to create a slanted and responsive div similar to the example image provided. Any assistance would be greatly appreciated. ...

Struggling with integrating JSON data into JqGrid

I've encountered a challenge with binding my Json data to a JqGrid. Within my Default.aspx.cs file, I have the following method: [WebMethod] public static string GetData() { CustomerHelper C = new CustomerHelper(); ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

Executing JavaScript code on ASP.NET page load

Inside my HTML code, there is a radio box styled using ASP.NET RadioButtonList with specific attributes. The second list item is set to be selected by default, however, the problem arises when the page loads as the function dis() is not being called. I wan ...

Splitting areas within a liquid vessel using bootstrap 5

My container is structured like this with divisions: <div class="container-fluid"> <div class="row"> <div class="col-3"> sidebar </div> <div class="col-7"> top slider </div> <di ...

Building an expandable vertical dropdown with Bootstrap that opens with a click

My goal is to design a vertical menu that expands when clicked, revealing 3 links for each item. I currently have the following setup: This is the initial layout: After clicking all items: The code I've implemented so far looks like this: <!DOC ...

Show the current time of a track using VueJS

Is there a way to have the time continuously update itself without needing to click on anything? When I press play, I want the seconds to automatically start updating from 0:00 until the end of the audio track. Currently, the time only updates when clicked ...