Error message "Undefined is not a function" occurred while using jQuery's .replace and scrollTop functions

I'm having issues with the scroll function in my code. It doesn't seem to be able to locate the ids in my HTML, even though I can't figure out why. I had a previous version that worked perfectly fine (unfortunately, I didn't save it D:). I thought I had rewritten it the same way as before, but apparently not.

Below is the JavaScript code:

$(document).ready(function() {

    $(function() {
        $(".navlist").on("click", function() {
            $(".navlist").removeClass("active");
            $(this).addClass("active");
        });
    });

    function goToByScroll(id){
      // Remove "link" from the ID
      id = $(id).replace("link", "");
      // Scroll
      $('html,body').animate({
          scrollTop: $("#"+id).offset().top}, 'slow');
    }

    $(".navbar > ul > li > a").click(function(e) { 
        // Prevent a page reload when a link is pressed
        e.preventDefault(); 
        // Call the scroll function
        goToByScroll($(this).attr("id"));           
    });

});

Here is the corresponding HTML code:

<body>

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
  <ul class="nav navbar-nav" >
    <li class="navbar-brand"><img width="100%" height="100%" src="sa.png"></li>
    <li class="navlist"><a id ="homelink" href="#">HOME</a></li>
    <li class="navlist"><a id = "portfoliolink" href="#">WORK</a></li>
    <li class="navlist"><a id = "contactlink" href="#">CONTACT</a></li>
  </ul>
</nav>

<section class="jumbotron_index"> 
  <p class= "scrollhome" id ="home"> scroll to home </p>
  <div class="content"> 
    <h1>  </h1>
    <h2>  
      <a href="" target="_blank"><img width="2%" height="2%" src="gh.png"></a></h2>
    <h3> </h3> 
    <p class= "scrollwork" id="portfolio"> scroll to work </p>  
  </div>
</section>


<div class="container middle">
//stuff here
</div>

<div class= "container bottom" id = "contact">
//stuff here
</div>

    <script src="bootstrap-3.0.0/dist/js/bootstrap.min.js"></script>

  </body>

Answer №1

It's important to note that jQuery does not include a built-in .replace function, as this is specifically designed for manipulating strings and not jQuery objects.

If you are passing the ID as a string, there is no need to use jQuery wrapping around it.

function scrollToId(id){

  id = id.replace("link", "");

  $('html,body').animate({
       scrollTop: $("#"+id).offset().top}, 'slow'
  );

}

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

Stop the sudden jump when following a hashed link using jQuery

Below is the code snippet I am working with: $( document ).ready(function() { $( '.prevent-default' ).click(function( event ) { event.preventDefault(); }); }); To prevent the window from jumping when a hashed anchor ...

What is the best way to display an entire string in a DataGridPro cell without truncating it with an ellipsis?

After reviewing all of the available DataGrid documentation, I am still unable to find a solution for displaying strings in multiple lines within a cell without ellipses. The current behavior is as follows: https://i.stack.imgur.com/TO8vB.png What I am a ...

Is there a way for me to store the retrieved information from an API into a global variable using Node.js?

function request2API(option){ const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2 const request = new XMLHttpRequest(); request.open('GET', urlStart + ChList[option].videosList + keyPrefix + key); request. ...

Managing time-intensive web service operations using JavaScript callbacks

One of the operations in my Web application involves a function that returns a value, which then needs to be passed to a web service method running separately from the application. This web service operation takes some time to complete and therefore must r ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

Extracting keys and values from a JSON string for analysis

My current code for the service now rest outbound call is functioning correctly. However, I am facing issues while trying to parse the JSON body in the second REST call and fetch values in the desired table format. try { var r = new sn_ws.RESTMessageV2 ...

Controller return 400 error after Ajax request

My Ajax call is pointing to a controller function: <script type="text/javascript"> $(document).ready(function () { $('#AddNote').click(function () { $('#AddNote').addClass("disabled"); ...

Encountering problem with rendering the header in the footer within a customized package built on react

I am currently working on creating a node package that consists of simple HTML elements. The package is named fmg_test_header. These are the files included in the package: header.jsx index.js package.json header.js function Header() { return "< ...

Utilizing a Recycled jQuery UI Themeroller Overlay

I'm looking to optimize css-loading bandwidth by reusing the overlay from jQuery UI for a specific section of my page. However, I'm encountering an issue where the overlay only covers a semi-transparent blackout of the entire page instead of just ...

Implementing a JavaScript Module Using JavaScript

I have encountered a simple problem. I am trying to use two JavaScript files: one following the module pattern and another one that calls the first one. I have tested all the code using Node.js and everything works fine when it is all in one file. However, ...

Position an element with absolute positioning to the right edge of a relative element

I have a situation where I need to align the end of a position absolute element with the end of a relative element, but the relative element's width is not fixed and may vary based on content. This scenario arises as I am creating a custom dropdown m ...

Using external URLs with added tracking parameters in Ionic 2

I am looking to create a unique http link to an external URL, extracted from my JSON data, within the detail pages of my app. Currently, I have the inappbrowser plugin installed that functions with a static URL directing to apple.com. However, I would lik ...

Transforming the DOM using jQuery

I am looking to manipulate the DOM using jQuery. This is the initial source code: <td class="name"><a href="position_details.php?x=-109&amp;y=95">21</a> </td> <td class="name"><a href="position_details.php?x=-109& ...

Open the CSV document

Why am I receiving an error stating ./vacancy-data.csv cannot be found when attempting to pass the csv file into the csvtojson npm package? The csv file is located in the same directory as the code below: var express = require('express'), route ...

Is it possible to prevent the selected option from being available in other select lists using AngularJS?

Can anyone help me figure out how to disable an option in one select list when it is selected in another using AngularJS? I have set up a select list for From Year and To Year with ng-repeat, which is working fine. Now, I just need to implement the functio ...

The attempt to fetch an additional 10 items through an AJAX call failed to meet expectations

I want to implement a feature where 10 items are loaded each time the "load more" button is clicked. Initially, I send the first 10 items and use dajaxice to load another set of 10 items everytime the button is pressed. Below is my view: def dj(request, ...

Finding the current HTML page URL in Ionic 2: A step-by-step guide

Can the URL of the current HTML page be obtained and then converted to PDF using the cordova-pdf-generator package? ...

Arranging CSS text in a parallel format and aligning it vertically

I am working on a layout with two columns of text placed side by side, where one column is right aligned and the other is left aligned. Below is my current code: .alignleft { float: left; } .alignright { float: right; } .list-unstyled { padding ...

Tips for generating a fresh array by conditionally including an extra property based on the comparison of two arrays

I am working with two different arrays: lockers: [ { locker_id: 1, label: { size: 1, label: "small" } }, { locker_id: 2, label: { size: 3, label: "medium" } }, { locker_id: 3 ...

Tips for reconnecting tinymce to a textarea following an ajax refresh

Whenever I submit a form with a tinymce textarea, the containing div gets reloaded using the following code: $('body').on('submit', '.comment_form', function (e) { e.preventDefault(); tinyMCE.triggerSave(); ...