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

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Unable to invoke any fineUploader functions within a callback function

My autoUpload is currently set to false because I prefer uploading the images manually to my backend. To achieve this, I need the file object first. In the onSubmitted event callbacks, I am attempting to pass the image's ID to the getFile method to re ...

Show real-time server responses using jQuery while waiting for the AJAX request to complete

I have a challenge in creating a function that displays the server response while waiting for Ajax to complete. Here's the scenario: I have selected 10 checkboxes. When I click the submit button, Ajax is triggered. On the server side, there is a loo ...

Reducing image size using CSS can result in blurry images on multiple web browsers

Encountering challenges with downscaled images in multiple browsers... The images must be downscaled to adapt to the browser size. Here is the code snippet: #pic-holder img { -moz-transform: rotate(0deg); /*image-rendering:-webkit-optimize-contras ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

Using JavaScript to Filter JSON Objects

After making a php ajax call, I have received the following JSON data that needs to be displayed to the users: JSON {"headers":{},"body":"{\"comuni\":[{\"datapresub\":\"08\/08 ...

Tips for resolving an issue with mongoose Model.create becoming unresponsive indefinitely

I'm having trouble understanding why my mongoose Model.create operation isn't completing successfully. The same connection is working well with other controller functions. vscode postman I am attempting to create a new document, but my code s ...

Extracting a variable established on the client side and passing it to a server-side node backend

I am currently working on creating a comments section for a web application. The front end of the app displays information about the threading level of each comment. When users submit comments, I need to pass this threading information to the back end in o ...

Why is my React component not being updated with Routes?

I'm new to using react-router and I'm struggling with it for the first time. Here is the code snippet: App.tsx import React from 'react'; logo = require('./logo.svg'); const { BrowserRouter as Router, Link, Route } = require ...

Is it better to define a function within useEffect or externally?

What is the reason behind defining the fetchData function inside the useEffect instead of outside? Link: https://github.com/zeit/next.js/blob/canary/examples/with-graphql-faunadb/lib/useFetch.js import { useState, useEffect } from 'react' exp ...

Upgrading to Angular 2: Utilizing ElementRef in ES5

Currently, I am facing a challenge in creating an Attribute directive for Angular 2 that would allow me to set multiple default HTML attributes using a single custom attribute. My intention is to apply this directive specifically to the input element. Howe ...

Material UI Snackbar background color not able to be changed

Currently, I'm working on an ErrorHandler component in React.JS that displays a Material UI Snackbar whenever it catches an error. The issue I'm facing is trying to change the background color of the Snackbar to red, which seems to be problematic ...

Caution: React detecting an active event listener on a scrolling-dependent 'touchstart' action

I am facing an issue with a React component that contains a Material-UI Slider. Whenever this component renders, I receive the following warning message: "Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking ...

Minimal - Combining a module with a parent component

To provide some background, I am utilizing bootstrap nav pills as triggers for bootstrap collapsibles. This is a simplified representation of the LESS code for bootstraps nav pills: .nav-pills { > li { // Active state &.active > a ...

variable identifier looping through elements

I'm attempting to assign a dynamic ID to my div using ng-repeat. Here's an example: <div id="$index" ng-repeat="repeat in results.myJsonResults"> <div id="$index" ng-click="saveID($index)" ng-repeat="subRepeat in results.myJsonResul ...

Core-pages with polymer core have no set height limit

I am embarking on my first project using Polymer. I have implemented core-pages to facilitate navigation between different pages. However, I am facing an issue where the pages are not displaying with a white background-color as intended in the css. You ca ...

What is the best way to make my text scroll horizontally if the container is not wide enough?

Instead of overwhelming you with code, I'll just share a link to the types of animations I've come across so far. Although these options are close to what I'm looking for, none of them are exactly right. The one that comes closest to my vis ...

display a new feature immediately upon the user's login

I encountered a scenario where the user is supposed to log in, and upon successful login, another component should be displayed. However, this functionality is not working as expected for me. I have to click the login button again or refresh the page to vi ...

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...

Preventing Duplicate Form Submissions in Rails 5 using jQuery

As a coding novice, I'm currently working on my Rails 5 app and implementing image cropping and uploading directly to AWS S3 from the client side using blueimp/jQuery-File-Upload. However, I have encountered an issue where multiple form submissions o ...